Imported Upstream version 0.4b42
[debian/dump] / 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. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  */
42
43 #ifndef lint
44 static const char rcsid[] =
45         "$Id: tape.c,v 1.92 2007/02/22 20:16:23 stelian Exp $";
46 #endif /* not lint */
47
48 #include <config.h>
49 #include <compatlfs.h>
50 #include <sys/types.h>
51 #include <errno.h>
52 #include <compaterr.h>
53 #include <system.h>
54 #include <setjmp.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59
60 #include <sys/param.h>
61 #include <sys/file.h>
62 #include <sys/mtio.h>
63 #include <sys/stat.h>
64
65 #ifdef  __linux__
66 #include <sys/time.h>
67 #include <time.h>
68 #ifdef HAVE_EXT2FS_EXT2_FS_H
69 #include <ext2fs/ext2_fs.h>
70 #else
71 #include <linux/ext2_fs.h>
72 #endif
73 #include <ext2fs/ext2fs.h>
74 #include <bsdcompat.h>
75 #else   /* __linux__ */
76 #ifdef sunos
77 #define quad_t int64_t
78 #include <sys/time.h>
79 #include <sys/fcntl.h>
80 #include <bsdcompat.h>
81 #else
82 #include <ufs/ufs/dinode.h>
83 #endif
84 #endif  /* __linux__ */
85 #ifdef DUMP_MACOSX
86 #include "darwin.h"
87 #endif
88 #include <protocols/dumprestore.h>
89
90 #ifdef HAVE_ZLIB
91 #include <zlib.h>
92 #endif /* HAVE_ZLIB */
93
94 #ifdef HAVE_BZLIB
95 #include <bzlib.h>
96 #endif /* HAVE_BZLIB */
97
98 #ifdef HAVE_LZO
99 #include <minilzo.h>
100 #endif /* HAVE_LZO */
101
102 #include "restore.h"
103 #include "extern.h"
104 #include "pathnames.h"
105
106 #ifdef USE_QFA
107 int             noresyncmesg = 0;
108 #endif /* USE_QFA */
109 static long     fssize = MAXBSIZE;
110 static int      mt = -1;
111 int             pipein = 0;
112 static int      magtapein = 0;          /* input is from magtape */
113 static char     magtape[MAXPATHLEN];
114 static char     magtapeprefix[MAXPATHLEN];
115 static int      blkcnt;
116 static int      numtrec;
117 static char     *tapebuf;               /* input buffer for read */
118 static int      bufsize;                /* buffer size without prefix */
119 static char     *tbufptr = NULL;        /* active tape buffer */
120 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
121 static char     *comprbuf;              /* uncompress work buf */
122 static size_t   comprlen;               /* size including prefix */
123 #endif
124 static union    u_spcl endoftapemark;
125 static long     blksread;               /* blocks read since last header */
126 static long     tpblksread = 0;         /* TP_BSIZE blocks read */
127 static long     tapesread;
128 static sigjmp_buf       restart;
129 static int      gettingfile = 0;        /* restart has a valid frame */
130 char            *host = NULL;
131
132 static int      ofile;
133 static char     *map;
134 static char     lnkbuf[MAXPATHLEN + 1];
135 static int      pathlen;
136
137 int             oldinofmt;      /* old inode format conversion required */
138 int             Bcvt;           /* Swap Bytes (for CCI or sun) */
139 static int      Qcvt;           /* Swap quads (for sun) */
140
141 #define FLUSHTAPEBUF()  blkcnt = ntrec + 1
142
143 static void      accthdr __P((struct s_spcl *));
144 static int       checksum __P((int *));
145 static void      findinode __P((struct s_spcl *));
146 static void      findtapeblksize __P((void));
147 static int       gethead __P((struct s_spcl *));
148 static int       converthead __P((struct s_spcl *));
149 static void      converttapebuf __P((struct tapebuf *));
150 static void      readtape __P((char *));
151 static void      setdumpnum __P((void));
152 #ifdef DUMP_MACOSX
153 static void      xtrfilefinderinfo __P((char *, size_t));
154 #endif
155
156 static u_int     swabi __P((u_int));
157 #if 0
158 static u_long    swabl __P((u_long));
159 #endif
160 static u_char   *swab64 __P((u_char *, int));
161 static u_char   *swab32 __P((u_char *, int));
162 static u_char   *swab16 __P((u_char *, int));
163 static void      terminateinput __P((void));
164 static void      xtrfile __P((char *, size_t));
165 static void      xtrlnkfile __P((char *, size_t));
166 static void      xtrlnkskip __P((char *, size_t));
167 static void      xtrmap __P((char *, size_t));
168 static void      xtrmapskip __P((char *, size_t));
169 static void      xtrskip __P((char *, size_t));
170 static void      xtrxattr __P((char *, size_t));
171 static void      setmagtapein __P((void));
172 static int       extractattr __P((char *));
173 static void      compareattr __P((char *));
174
175 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
176 static void     newcomprbuf __P((int));
177 static void     (*readtape_func) __P((char *));
178 static void     readtape_set __P((char *));
179 static void     readtape_uncompr __P((char *));
180 static void     readtape_comprfile __P((char *));
181 static void     readtape_comprtape __P((char *));
182 static char     *decompress_tapebuf __P((struct tapebuf *, int));
183 static void     msg_read_error __P((char *));
184 #endif
185 static int      read_a_block __P((int, char *, size_t, long *));
186 #define PREFIXSIZE      sizeof(struct tapebuf)
187
188 #define COMPARE_ONTHEFLY 1
189
190 #if COMPARE_ONTHEFLY
191 static int      ifile;          /* input file for compare */
192 static int      cmperror;       /* compare error */
193 static void     xtrcmpfile __P((char *, size_t));
194 static void     xtrcmpskip __P((char *, size_t));
195 #endif
196
197 static int readmapflag;
198 static int readingmaps;         /* set to 1 while reading the maps */
199
200 static char xattrbuf[XATTR_MAXSIZE];
201 static int xattrlen;
202
203 #ifdef DUMP_MACOSX
204 static DumpFinderInfo   gFndrInfo;
205 #endif
206
207 /*
208  * Set up an input source. This is called from main.c before setup() is.
209  */
210 void
211 setinput(char *source)
212 {
213         int i;
214         char *n;
215
216         FLUSHTAPEBUF();
217         if (bflag)
218                 newtapebuf(ntrec);
219         else
220                 newtapebuf(NTREC > HIGHDENSITYTREC ? NTREC : HIGHDENSITYTREC);
221         terminal = stdin;
222
223 #ifdef RRESTORE
224         if ((n = strchr(source, ':'))) {
225                 for (i = 0; i < (n - source); i++) {
226                         if (source[i] == '/')
227                                 break;
228                 }
229                 if (source[i] != '/') {
230                         host = source;
231                         source = strchr(host, ':');
232                         *source++ = '\0';
233                         if (rmthost(host) == 0)
234                                 exit(1);
235                 }
236         } else
237 #endif
238         if (strcmp(source, "-") == 0) {
239                 /*
240                  * Since input is coming from a pipe we must establish
241                  * our own connection to the terminal.
242                  */
243                 terminal = fopen(_PATH_TTY, "r");
244                 if (terminal == NULL) {
245                         warn("cannot open %s", _PATH_TTY);
246                         terminal = fopen(_PATH_DEVNULL, "r");
247                         if (terminal == NULL)
248                                 err(1, "cannot open %s", _PATH_DEVNULL);
249                 }
250                 pipein++;
251         }
252         setuid(getuid());       /* no longer need or want root privileges */
253         if (Mflag) {
254                 strncpy(magtapeprefix, source, MAXPATHLEN);
255                 magtapeprefix[MAXPATHLEN-1] = '\0';
256                 snprintf(magtape, MAXPATHLEN, "%s%03d", source, 1);
257         }
258         else
259                 strncpy(magtape, source, MAXPATHLEN);
260         magtape[MAXPATHLEN - 1] = '\0';
261 }
262
263 void
264 newtapebuf(long size)
265 {
266         static int tapebufsize = -1;
267
268         ntrec = size;
269         bufsize = ntrec * TP_BSIZE;
270         if (size <= tapebufsize)
271                 return;
272         if (tapebuf != NULL)
273                 free(tapebuf);
274         tapebuf = malloc(size * TP_BSIZE + sizeof(struct tapebuf));
275         if (tapebuf == NULL)
276                 errx(1, "Cannot allocate space for tape buffer");
277         tapebufsize = size;
278 }
279
280 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
281 static void
282 newcomprbuf(int size)
283 {
284         size_t buf_size = (size+1) * TP_BSIZE + sizeof(struct tapebuf);
285         if (buf_size <= comprlen)
286                 return;
287         comprlen = buf_size;
288         if (comprbuf != NULL)
289                 free(comprbuf);
290         comprbuf = malloc(comprlen);
291         if (comprbuf == NULL)
292                 errx(1, "Cannot allocate space for decompress buffer");
293 }
294 #endif /* HAVE_ZLIB || HAVE_BZLIB || HAVE_LZO */
295
296 /*
297  * Verify that the tape drive can be accessed and
298  * that it actually is a dump tape.
299  */
300 void
301 setup(void)
302 {
303         int i, j, *ip, bot_code;
304         struct STAT stbuf;
305         char *temptape;
306
307         Vprintf(stdout, "Verify tape and initialize maps\n");
308         if (Afile == NULL && bot_script) {
309                 msg("Launching %s\n", bot_script);
310                 bot_code = system_command(bot_script, magtape, 1);
311                 if (bot_code != 0 && bot_code != 1) {
312                         msg("Restore aborted by the beginning of tape script\n");
313                         exit(1);
314                 }
315         }
316
317         if (Afile)
318                 temptape = Afile;
319         else
320                 temptape = magtape;
321
322 #ifdef RRESTORE
323         if (!Afile && host)
324                 mt = rmtopen(temptape, O_RDONLY);
325         else
326 #endif
327         if (pipein)
328                 mt = 0;
329         else
330                 mt = OPEN(temptape, O_RDONLY, 0);
331         if (mt < 0)
332                 err(1, "%s", temptape);
333         if (!Afile) {
334                 volno = 1;
335                 setmagtapein();
336                 setdumpnum();
337         }
338 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
339         readtape_func = readtape_set;
340 #if defined(HAVE_LZO)
341         if (lzo_init() != LZO_E_OK) {
342           msg("internal error - lzo_init failed \n");
343           exit(1);
344         }
345 #endif
346 #endif
347         FLUSHTAPEBUF();
348         findtapeblksize();
349         cvtflag = 0;
350         if (gethead(&spcl) == FAIL) {
351                 blkcnt--; /* push back this block */
352                 blksread--;
353                 tpblksread--;
354                 cvtflag++;
355                 if (gethead(&spcl) == FAIL)
356                         errx(1, "Tape is not a dump tape");
357                 fprintf(stderr, "Converting to new file system format.\n");
358         }
359
360         if (zflag) {
361                 fprintf(stderr, "Dump tape is compressed.\n");
362 #if !defined(HAVE_ZLIB) && !defined(HAVE_BZLIB) && !defined(HAVE_LZO)
363                 errx(1,"This restore version doesn't support decompression");
364 #endif /* !HAVE_ZLIB && !HAVE_BZLIB */
365         }
366         if (pipein) {
367                 endoftapemark.s_spcl.c_magic = cvtflag ? OFS_MAGIC : NFS_MAGIC;
368                 endoftapemark.s_spcl.c_type = TS_END;
369                 ip = (int *)&endoftapemark;
370                 j = sizeof(union u_spcl) / sizeof(int);
371                 i = 0;
372                 do
373                         i += *ip++;
374                 while (--j);
375                 endoftapemark.s_spcl.c_checksum = CHECKSUM - i;
376         }
377         if (vflag || command == 't' || command == 'C')
378                 printdumpinfo();
379 #ifdef USE_QFA
380         if (tapeposflag && (unsigned long)spcl.c_date != qfadumpdate)
381                 errx(1, "different QFA/dumpdates detected\n");
382 #endif
383         if (filesys[0] == '\0') {
384                 char *dirptr;
385                 strncpy(filesys, spcl.c_filesys, NAMELEN);
386                 filesys[NAMELEN - 1] = '\0';
387                 dirptr = strstr(filesys, " (dir");
388                 if (dirptr != NULL)
389                         *dirptr = '\0';
390         }
391         dumptime = spcl.c_ddate;
392         dumpdate = spcl.c_date;
393         if (STAT(".", &stbuf) < 0)
394                 err(1, "cannot stat .");
395         if (stbuf.st_blksize > 0 && stbuf.st_blksize < TP_BSIZE )
396                 fssize = TP_BSIZE;
397         if (stbuf.st_blksize >= TP_BSIZE && stbuf.st_blksize <= MAXBSIZE)
398                 fssize = stbuf.st_blksize;
399         if (((fssize - 1) & fssize) != 0)
400                 errx(1, "bad block size %ld", fssize);
401         if (spcl.c_volume != 1)
402                 errx(1, "Tape is not volume 1 of the dump");
403         if (gethead(&spcl) == FAIL) {
404                 Dprintf(stdout, "header read failed at %ld blocks\n", (long)blksread);
405                 panic("no header after volume mark!\n");
406         }
407         readingmaps = 1;
408         findinode(&spcl);
409         if (spcl.c_type != TS_CLRI)
410                 errx(1, "Cannot find file removal list");
411         maxino = (spcl.c_count * TP_BSIZE * NBBY) + 1;
412         map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
413         if (map == NULL)
414                 errx(1, "no memory for active inode map");
415         usedinomap = map;
416         curfile.action = USING;
417         getfile(xtrmap, xtrmapskip);
418         while (spcl.c_type == TS_ADDR) {
419                 /* Recompute maxino and the map */
420                 dump_ino_t oldmaxino = maxino;
421                 maxino += (spcl.c_count * TP_BSIZE * NBBY) + 1;
422                 resizemaps(oldmaxino, maxino);
423                 map = usedinomap;
424
425                 spcl.c_dinode.di_size = spcl.c_count * TP_BSIZE;
426                 getfile(xtrmap, xtrmapskip);
427         }
428         Dprintf(stdout, "maxino = %lu\n", (unsigned long)maxino);
429         if (spcl.c_type != TS_BITS) {
430                 if (spcl.c_type == TS_END) {
431                         msg("Cannot find file dump list, assuming empty tape\n");
432                         exit(0);
433                 }
434                 errx(1, "Cannot find file dump list");
435         }
436         map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
437         if (map == (char *)NULL)
438                 errx(1, "no memory for file dump list");
439         dumpmap = map;
440         curfile.action = USING;
441         getfile(xtrmap, xtrmapskip);
442         while (spcl.c_type == TS_ADDR) {
443                 spcl.c_dinode.di_size = spcl.c_count * TP_BSIZE;
444                 getfile(xtrmap, xtrmapskip);
445         }
446         /*
447          * If there may be whiteout entries on the tape, pretend that the
448          * whiteout inode exists, so that the whiteout entries can be
449          * extracted.
450          */
451         if (oldinofmt == 0)
452                 SETINO(WINO, dumpmap);
453         readingmaps = 0;
454         findinode(&spcl);
455 }
456
457 /*
458  * Prompt user to load a new dump volume.
459  * "Nextvol" is the next suggested volume to use.
460  * This suggested volume is enforced when doing full
461  * or incremental restores, but can be overridden by
462  * the user when only extracting a subset of the files.
463  */
464 void
465 getvol(long nextvol)
466 {
467         long newvol = 0, wantnext = 0, i;
468         long saved_blksread = 0, saved_tpblksread = 0;
469         union u_spcl tmpspcl;
470 #       define tmpbuf tmpspcl.s_spcl
471         char buf[TP_BSIZE];
472         int haderror = 0, bot_code = 1;
473
474         if (nextvol == 1) {
475                 tapesread = 0;
476                 gettingfile = 0;
477                 tpblksread = 0;
478                 blksread = 0;
479         }
480         if (pipein) {
481                 if (nextvol != 1)
482                         panic("Changing volumes on pipe input?\n");
483                 if (volno == 1)
484                         return;
485                 goto gethdr;
486         }
487         saved_blksread = blksread;
488         saved_tpblksread = tpblksread;
489 #if defined(USE_QFA) && defined(sunos)
490         if (createtapeposflag || tapeposflag) 
491                 close(fdsmtc);
492 #endif
493 again:
494         if (pipein)
495                 exit(1); /* pipes do not get a second chance */
496         if (aflag || curfile.action != SKIP) {
497                 newvol = nextvol;
498                 wantnext = 1;
499         } else {
500                 newvol = 0;
501                 wantnext = 0;
502         }
503         while (newvol <= 0) {
504                 if (tapesread == 0) {
505                         fprintf(stderr, "%s%s%s%s%s",
506                             "You have not read any volumes yet.\n",
507                             "Unless you know which volume your",
508                             " file(s) are on you should start\n",
509                             "with the last volume and work",
510                             " towards the first.\n");
511                 } else {
512                         fprintf(stderr, "You have read volumes");
513                         strcpy(buf, ": ");
514                         for (i = 1; i < 32; i++)
515                                 if (tapesread & (1 << i)) {
516                                         fprintf(stderr, "%s%ld", buf, (long)i);
517                                         strcpy(buf, ", ");
518                                 }
519                         fprintf(stderr, "\n");
520                 }
521                 do      {
522                         fprintf(stderr, "Specify next volume # (none if no more volumes): ");
523                         (void) fflush(stderr);
524                         (void) fgets(buf, TP_BSIZE, terminal);
525                 } while (!feof(terminal) && buf[0] == '\n');
526                 if (feof(terminal))
527                         exit(1);
528                 if (!strcmp(buf, "none\n")) {
529                         terminateinput();
530                         return;
531                 }
532                 newvol = atoi(buf);
533                 if (newvol <= 0) {
534                         fprintf(stderr,
535                             "Volume numbers are positive numerics\n");
536                 }
537         }
538         if (newvol == volno) {
539                 tapesread |= 1 << volno;
540 #if defined(USE_QFA) && defined(sunos)
541                 if (createtapeposflag || tapeposflag) {
542                         if (OpenSMTCmt(magtape) < 0) {
543                                 volno = -1;
544                                 haderror = 1;
545                                 goto again;
546                         }
547                 }
548 #endif  /* USE_QFA */
549                 return;
550         }
551         closemt();
552
553         /* 
554          * if using an archive file, reset its name so readtape()
555          * could properly use remote access.
556          */
557         Afile = NULL;
558
559         if (Mflag) {
560                 snprintf(magtape, MAXPATHLEN, "%s%03ld", magtapeprefix, newvol);
561                 magtape[MAXPATHLEN - 1] = '\0';
562         }
563         if (bot_script && !haderror) {
564                 msg("Launching %s\n", bot_script);
565                 bot_code = system_command(bot_script, magtape, newvol);
566                 if (bot_code != 0 && bot_code != 1) {
567                         msg("Restore aborted by the beginning of tape script\n");
568                         exit(1);
569                 }
570         }
571         if (haderror || (bot_code && !Mflag)) {
572                 haderror = 0;
573                 if (compare_errors)
574                         fprintf(stderr, "%d compare errors so far\n", compare_errors);
575 #ifdef sunos
576                 fprintf(stderr, "Mount volume %ld\n", (long)newvol);
577 #else
578                 fprintf(stderr, "Mount tape volume %ld\n", (long)newvol);
579 #endif
580                 fprintf(stderr, "Enter ``none'' if there are no more tapes\n");
581 #ifdef sunos
582                 fprintf(stderr, "then enter volume name (default: %s) ", magtape);
583 #else
584                 fprintf(stderr, "otherwise enter tape name (default: %s) ", magtape);
585 #endif
586                 (void) fflush(stderr);
587                 (void) fgets(buf, TP_BSIZE, terminal);
588                 if (feof(terminal))
589                         exit(1);
590                 if (!strcmp(buf, "none\n")) {
591                         terminateinput();
592                         return;
593                 }
594                 if (buf[0] != '\n') {
595                         char *pos;
596                         (void) strncpy(magtape, buf, sizeof(magtape));
597                         magtape[sizeof(magtape) - 1] = '\0';
598                         if ((pos = strchr(magtape, '\n'))) 
599                                 magtape[pos - magtape] = '\0';
600                 }
601         }
602 #if defined(USE_QFA) && defined(sunos)
603         if (createtapeposflag || tapeposflag) {
604                 if (OpenSMTCmt(magtape) < 0) {
605                         volno = -1;
606                         haderror = 1;
607                         goto again;
608                 }
609         }
610 #endif  /* USE_QFA */
611 #ifdef RRESTORE
612         if (host)
613                 mt = rmtopen(magtape, O_RDONLY);
614         else
615 #endif
616                 mt = OPEN(magtape, O_RDONLY, 0);
617
618         if (mt == -1) {
619                 fprintf(stderr, "Cannot open %s\n", magtape);
620                 volno = -1;
621                 haderror = 1;
622                 goto again;
623         }
624 gethdr:
625         setmagtapein();
626 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
627         readtape_func = readtape_set;
628 #endif
629         volno = newvol;
630         setdumpnum();
631         FLUSHTAPEBUF();
632         findtapeblksize();
633         if (gethead(&tmpbuf) == FAIL) {
634                 Dprintf(stdout, "header read failed at %ld blocks\n", (long)blksread);
635                 fprintf(stderr, "tape is not dump tape\n");
636                 volno = 0;
637                 haderror = 1;
638                 blksread = saved_blksread;
639                 tpblksread = saved_tpblksread;
640                 goto again;
641         }
642         if (tmpbuf.c_volume != volno) {
643                 fprintf(stderr, "Wrong volume (%d)\n", tmpbuf.c_volume);
644                 volno = 0;
645                 haderror = 1;
646                 blksread = saved_blksread;
647                 tpblksread = saved_tpblksread;
648                 goto again;
649         }
650         if (tmpbuf.c_date != dumpdate || tmpbuf.c_ddate != dumptime) {
651                 fprintf(stderr, "Wrong dump date\n\tgot: %s",
652 #ifdef sunos
653                         ctime(&tmpbuf.c_date));
654 #else
655                         ctime4(&tmpbuf.c_date));
656 #endif
657                 fprintf(stderr, "\twanted: %s", ctime(&dumpdate));
658                 volno = 0;
659                 haderror = 1;
660                 blksread = saved_blksread;
661                 tpblksread = saved_tpblksread;
662                 goto again;
663         }
664         tapesread |= 1 << volno;
665         /*
666          * If continuing from the previous volume, skip over any
667          * blocks read already at the end of the previous volume.
668          *
669          * If coming to this volume at random, skip to the beginning
670          * of the next record.
671          */
672         if (zflag) {
673                 fprintf(stderr, "Dump tape is compressed.\n");
674 #if !defined(HAVE_ZLIB) && !defined(HAVE_BZLIB) && !defined(HAVE_LZO)
675                 errx(1,"This restore version doesn't support decompression");
676 #endif /* !HAVE_ZLIB && !HAVE_BZLIB */
677         }
678         Dprintf(stdout, "read %ld recs, tape starts with %ld\n",
679                 tpblksread - 1, (long)tmpbuf.c_firstrec);
680         if (tmpbuf.c_type == TS_TAPE && (tmpbuf.c_flags & DR_NEWHEADER)) {
681                 if (!wantnext) {
682                         tpblksread = tmpbuf.c_firstrec + 1;
683                         for (i = tmpbuf.c_count; i > 0; i--)
684                                 readtape(buf);
685                 } else if (tmpbuf.c_firstrec > 0 &&
686                            tmpbuf.c_firstrec < tpblksread - 1) {
687                         /*
688                          * -1 since we've read the volume header
689                          */
690                         i = tpblksread - tmpbuf.c_firstrec - 1;
691                         Dprintf(stderr, "Skipping %ld duplicate record%s.\n",
692                                 (long)i, i > 1 ? "s" : "");
693                         while (--i >= 0)
694                                 readtape(buf);
695                 }
696         }
697         if (curfile.action == USING) {
698                 if (volno == 1)
699                         panic("active file into volume 1\n");
700                 return;
701         }
702         /*
703          * Skip up to the beginning of the next record
704          */
705         if (tmpbuf.c_type == TS_TAPE && (tmpbuf.c_flags & DR_NEWHEADER))
706                 for (i = tmpbuf.c_count; i > 0; i--)
707                         readtape(buf);
708         (void) gethead(&spcl);
709         findinode(&spcl);
710         if (gettingfile) {
711                 gettingfile = 0;
712                 siglongjmp(restart, 1);
713         }
714 }
715
716 /*
717  * Handle unexpected EOF.
718  */
719 static void
720 terminateinput(void)
721 {
722
723         if (gettingfile && curfile.action == USING) {
724                 printf("Warning: %s %s\n",
725                     "End-of-input encountered while extracting", curfile.name);
726         }
727         curfile.name = "<name unknown>";
728         curfile.action = UNKNOWN;
729         curfile.dip = NULL;
730         curfile.ino = maxino;
731         if (gettingfile) {
732                 gettingfile = 0;
733                 siglongjmp(restart, 1);
734         }
735 }
736
737 /*
738  * handle multiple dumps per tape by skipping forward to the
739  * appropriate one.
740  */
741 static void
742 setdumpnum(void)
743 {
744         struct mtop tcom;
745
746         if (dumpnum == 1 || volno != 1)
747                 return;
748         if (pipein)
749                 errx(1, "Cannot have multiple dumps on pipe input");
750         tcom.mt_op = MTFSF;
751         tcom.mt_count = dumpnum - 1;
752 #ifdef RRESTORE
753         if (host) {
754                 if (rmtioctl(MTFSF, dumpnum - 1) < 0) {
755                         fprintf(stderr, "rmtioctl MTFSF: %s\n", strerror(errno));
756             exit(1);
757                 }
758         } else
759 #endif
760                 if (ioctl(mt, (int)MTIOCTOP, (char *)&tcom) < 0) {
761                         fprintf(stderr, "rmtioctl MTFSF: %s\n", strerror(errno));
762                         exit(1);
763                         /* warn("ioctl MTFSF"); */
764                 }
765 }
766
767 void
768 printdumpinfo(void)
769 {
770 #ifdef sunos
771         Vprintf(stdout, "Dump   date: %s", ctime(&spcl.c_date));
772         Vprintf(stdout, "Dumped from: %s",
773             (spcl.c_ddate == 0) ? "the epoch\n" : ctime(&spcl.c_ddate));
774         if (spcl.c_host[0] == '\0')
775                 return;
776         Vprintf(stdout, "Level %d dump of %s on %s:%s\n",
777                 spcl.c_level, spcl.c_filesys, spcl.c_host, spcl.c_dev);
778         Vprintf(stdout, "Label: %s\n", spcl.c_label);
779 #else
780         fprintf(stdout, "Dump   date: %s", ctime4(&spcl.c_date));
781         fprintf(stdout, "Dumped from: %s",
782             (spcl.c_ddate == 0) ? "the epoch\n" : ctime4(&spcl.c_ddate));
783         if (spcl.c_host[0] == '\0')
784                 return;
785         fprintf(stdout, "Level %d dump of %s on %s:%s\n",
786                 spcl.c_level, spcl.c_filesys, spcl.c_host, spcl.c_dev);
787         fprintf(stdout, "Label: %s\n", spcl.c_label);
788 #endif
789 }
790
791 void 
792 printvolinfo(void)
793 {
794         int i;
795
796         if (volinfo[1] == ROOTINO) {
797                 printf("Starting inode numbers by volume:\n");
798                 for (i = 1; i < (int)TP_NINOS && volinfo[i] != 0; ++i)
799                         printf("\tVolume %d: %lu\n", i, (unsigned long)volinfo[i]);
800         }
801 }
802
803
804 int
805 extractfile(struct entry *ep, int doremove)
806 {
807         unsigned int flags;
808         mode_t mode;
809         struct timeval timep[2];
810         char *name = myname(ep);
811
812         /* If removal is requested (-r mode) do remove it unless
813          * we are extracting a metadata only inode */
814         if (spcl.c_flags & DR_METAONLY) {
815                 Vprintf(stdout, "file %s is metadata only\n", name);
816         }
817         else {
818                 if (doremove) {
819                         removeleaf(ep);
820                         ep->e_flags &= ~REMOVED;
821                 }
822         }
823
824         curfile.name = name;
825         curfile.action = USING;
826 #if defined(__linux__) || defined(sunos)
827         timep[0].tv_sec = curfile.dip->di_atime.tv_sec;
828         timep[0].tv_usec = curfile.dip->di_atime.tv_usec;
829         timep[1].tv_sec = curfile.dip->di_mtime.tv_sec;
830         timep[1].tv_usec = curfile.dip->di_mtime.tv_usec;
831 #else   /* __linux__ || sunos */
832         timep[0].tv_sec = curfile.dip->di_atime;
833         timep[0].tv_usec = curfile.dip->di_atimensec / 1000;
834         timep[1].tv_sec = curfile.dip->di_mtime;
835         timep[1].tv_usec = curfile.dip->di_mtimensec / 1000;
836 #endif  /* __linux__ */
837         mode = curfile.dip->di_mode;
838         flags = curfile.dip->di_flags;
839         switch (mode & IFMT) {
840
841         default:
842                 fprintf(stderr, "%s: unknown file mode 0%o\n", name, mode);
843                 skipfile();
844                 return (FAIL);
845
846         case IFSOCK:
847                 Vprintf(stdout, "skipped socket %s\n", name);
848                 skipfile();
849                 return (GOOD);
850
851         case IFDIR:
852         {
853                 int ret;
854                 if (mflag) {
855                         if (ep == NULL || ep->e_flags & EXTRACT)
856                                 panic("unextracted directory %s\n", name);
857                         skipfile();
858                         return (GOOD);
859                 }
860                 Vprintf(stdout, "extract dir %s\n", name);
861                 ret = genliteraldir(name, curfile.ino);
862                 extractattr(name);
863                 return ret;
864         }
865
866         case IFLNK:
867         {
868 #ifdef HAVE_LCHOWN
869                 uid_t luid = curfile.dip->di_uid;
870                 gid_t lgid = curfile.dip->di_gid;
871 #endif
872                 if (! (spcl.c_flags & DR_METAONLY)) {
873                         lnkbuf[0] = '\0';
874                         pathlen = 0;
875                         getfile(xtrlnkfile, xtrlnkskip);
876                         if (pathlen == 0) {
877                                 Vprintf(stdout,
878                                     "%s: zero length symbolic link (ignored)\n", name);
879                                 return (GOOD);
880                         }
881                         if (linkit(lnkbuf, name, SYMLINK) == FAIL)
882                                 return (FAIL);
883                 }
884                 else
885                         skipfile();
886
887 #ifdef HAVE_LCHOWN
888                 (void) lchown(name, luid, lgid);
889 #endif
890                 extractattr(name);
891                 return (GOOD);
892         }
893
894         case IFIFO:
895                 Vprintf(stdout, "extract fifo %s\n", name);
896                 if (Nflag) {
897                         skipfile();
898                         return (GOOD);
899                 }
900                 if (! (spcl.c_flags & DR_METAONLY)) {
901                         if (uflag && !Nflag)
902                                 (void)unlink(name);
903                         if (mkfifo(name, mode) < 0) {
904                                 warn("%s: cannot create fifo", name);
905                                 skipfile();
906                                 return (FAIL);
907                         }
908                 }
909                 (void) chown(name, curfile.dip->di_uid, curfile.dip->di_gid);
910                 (void) chmod(name, mode);
911                 extractattr(name);
912                 utimes(name, timep);
913                 if (flags)
914 #ifdef  __linux__
915                         (void) lsetflags(name, flags);
916 #else
917 #ifdef sunos
918                         {
919                         warn("%s: cannot call chflags", name);
920                         /* (void) chflags(name, flags); */
921                         }
922 #else
923                         (void) chflags(name, flags);
924 #endif
925 #endif
926                 skipfile();
927                 return (GOOD);
928
929         case IFCHR:
930         case IFBLK:
931                 Vprintf(stdout, "extract special file %s\n", name);
932                 if (Nflag) {
933                         skipfile();
934                         return (GOOD);
935                 }
936                 if (! (spcl.c_flags & DR_METAONLY)) {
937                         if (uflag)
938                                 (void)unlink(name);
939                         if (mknod(name, mode, (int)curfile.dip->di_rdev) < 0) {
940                                 warn("%s: cannot create special file", name);
941                                 skipfile();
942                                 return (FAIL);
943                         }
944                 }
945                 (void) chown(name, curfile.dip->di_uid, curfile.dip->di_gid);
946                 (void) chmod(name, mode);
947                 extractattr(name);
948                 utimes(name, timep);
949                 if (flags)
950 #ifdef  __linux__
951                         {
952                         warn("%s: lsetflags called on a special file", name);
953                         (void) lsetflags(name, flags);
954                         }
955 #else
956 #ifdef sunos
957                         {
958                         warn("%s: cannot call chflags on a special file", name);
959                         /* (void) chflags(name, flags); */
960                         }
961 #else
962                         {
963                         warn("%s: chflags called on a special file", name);
964                         (void) chflags(name, flags);
965                         }
966 #endif
967 #endif
968                 skipfile();
969                 return (GOOD);
970
971         case IFREG:
972         {
973                 uid_t luid = curfile.dip->di_uid;
974                 gid_t lgid = curfile.dip->di_gid;
975
976                 Vprintf(stdout, "extract file %s\n", name);
977                 if (Nflag) {
978                         skipfile();
979                         return (GOOD);
980                 }
981                 if (! (spcl.c_flags & DR_METAONLY)) {
982                         if (uflag)
983                                 (void)unlink(name);
984                         if ((ofile = OPEN(name, O_WRONLY | O_CREAT | O_TRUNC,
985                             0666)) < 0) {
986                                 warn("%s: cannot create file", name);
987                                 skipfile();
988                                 return (FAIL);
989                         }
990                         getfile(xtrfile, xtrskip);
991                         (void) close(ofile);
992                 }
993                 else
994                         skipfile();
995                 (void) chown(name, luid, lgid);
996                 (void) chmod(name, mode);
997                 extractattr(name);
998                 utimes(name, timep);
999                 if (flags)
1000 #ifdef  __linux__
1001                         (void) lsetflags(name, flags);
1002 #else
1003 #ifdef sunos
1004                         {
1005                         warn("%s: cannot call chflags", name);
1006                         /* (void) chflags(name, flags); */
1007                         }
1008 #else
1009                         (void) chflags(name, flags);
1010 #endif
1011 #endif
1012                 return (GOOD);
1013         }
1014         }
1015         /* NOTREACHED */
1016 }
1017
1018 static int
1019 extractattr(char *path)
1020 {
1021         while (spcl.c_flags & DR_EXTATTRIBUTES) {
1022                 switch (spcl.c_extattributes) {
1023                 case EXT_MACOSFNDRINFO:
1024 #ifdef DUMP_MACOSX
1025                         (void)extractfinderinfoufs(path);
1026 #else
1027                         msg("MacOSX not supported in this version, skipping\n");
1028                         skipfile();
1029 #endif
1030                         break;
1031                 case EXT_MACOSRESFORK:
1032 #ifdef DUMP_MACOSX
1033                         (void)extractresourceufs(path);
1034 #else
1035                         msg("MacOSX not supported in this version, skipping\n");
1036                         skipfile();
1037 #endif
1038                         break;
1039                 case EXT_XATTR: {
1040                         char xattr[XATTR_MAXSIZE];
1041                         
1042                         if (readxattr(xattr) == GOOD) {
1043                                 xattr_extract(path, xattr);
1044                                 break;
1045                         }
1046                 }
1047                 default:
1048                         msg("unexpected inode extension %ld, skipping\n", spcl.c_extattributes);
1049                         skipfile();
1050                         break;
1051                 }
1052         }
1053         return GOOD;
1054 }
1055
1056 #ifdef DUMP_MACOSX
1057 int
1058 extractfinderinfoufs(char *name)
1059 {
1060         int err;
1061         char                    oFileRsrc[MAXPATHLEN];
1062         int flags;
1063         mode_t mode;
1064         struct timeval timep[2];
1065         u_int32_t       uid;
1066         u_int32_t       gid;
1067         char    path[MAXPATHLEN], fname[MAXPATHLEN];
1068
1069         curfile.name = name;
1070         curfile.action = USING;
1071         timep[0].tv_sec = curfile.dip->di_atime.tv_sec;
1072         timep[0].tv_usec = curfile.dip->di_atime.tv_usec;
1073         timep[1].tv_sec = curfile.dip->di_mtime.tv_sec;
1074         timep[1].tv_usec = curfile.dip->di_mtime.tv_usec;
1075         mode = curfile.dip->di_mode;
1076         flags = curfile.dip->di_flags;
1077         uid = curfile.dip->di_uid;
1078         gid =  curfile.dip->di_gid;
1079
1080         switch (mode & IFMT) {
1081
1082         default:
1083                 fprintf(stderr, "%s: (extr. finfoufs) unknown file mode 0%o\n", name, mode);
1084                 skipfile();
1085                 return (FAIL);
1086
1087         case IFDIR:
1088                 fprintf(stderr, "%s: (extr. finfoufs[IFDIR]) unknown file mode 0%o\n", name, mode);
1089                 skipfile();
1090                 return (FAIL);
1091
1092         case IFLNK:
1093                 skipfile();
1094                 return (GOOD);
1095
1096         case IFREG:
1097                 Vprintf(stdout, "extract finderinfo file %s\n", name);
1098                 if (Nflag) {
1099                         skipfile();
1100                         return (GOOD);
1101                 }
1102                 getfile(xtrfilefinderinfo, xtrskip);
1103
1104                 GetPathFile(name, path, fname);
1105                 strcpy(oFileRsrc, path);
1106                 strcat(oFileRsrc, "._");
1107                 strcat(oFileRsrc, fname);
1108
1109                 if ((err = CreateAppleDoubleFileRes(oFileRsrc, &gFndrInfo.fndrinfo,
1110                                 mode, flags, timep, uid, gid)) != 0) {
1111                         fprintf(stderr, "%s: cannot create finderinfo: %s\n",
1112                         name, strerror(errno));
1113                         skipfile();
1114                         return (FAIL);
1115                 }
1116                 return (GOOD);
1117         }
1118         /* NOTREACHED */
1119 }
1120
1121
1122 int
1123 extractresourceufs(char *name)
1124 {
1125         char                    oFileRsrc[MAXPATHLEN];
1126         int flags;
1127         mode_t mode;
1128         struct timeval timep[2];
1129         char    path[MAXPATHLEN], fname[MAXPATHLEN];
1130         ASDHeaderPtr    hp;
1131         ASDEntryPtr     ep;
1132         u_long  loff;
1133          u_int32_t      uid;
1134         u_int32_t       gid;
1135         u_int64_t       di_size;
1136         char            *p;
1137         char            buf[1024];
1138
1139         curfile.name = name;
1140         curfile.action = USING;
1141         timep[0].tv_sec = curfile.dip->di_atime.tv_sec;
1142         timep[0].tv_usec = curfile.dip->di_atime.tv_usec;
1143         timep[1].tv_sec = curfile.dip->di_mtime.tv_sec;
1144         timep[1].tv_usec = curfile.dip->di_mtime.tv_usec;
1145         mode = curfile.dip->di_mode;
1146         flags = curfile.dip->di_flags;
1147         uid = curfile.dip->di_uid;
1148         gid =  curfile.dip->di_gid;
1149         di_size = curfile.dip->di_size;
1150
1151         switch (mode & IFMT) {
1152
1153         default:
1154                 fprintf(stderr, "%s: (extr. resufs) unknown file mode 0%o\n", name, mode);
1155                 skipfile();
1156                 return (FAIL);
1157
1158         case IFDIR:
1159                 fprintf(stderr, "%s: (extr. resufs [IFDIR]) unknown file mode 0%o\n", name, mode);
1160                 skipfile();
1161                 return (FAIL);
1162
1163         case IFLNK:
1164                 skipfile();
1165                 return (GOOD);
1166
1167         case IFREG:
1168                 Vprintf(stdout, "extract resource file %s\n", name);
1169                 if (Nflag) {
1170                         skipfile();
1171                         return (GOOD);
1172                 }
1173
1174                 GetPathFile(name, path, fname);
1175                 strcpy(oFileRsrc, path);
1176                 strcat(oFileRsrc, "._");
1177                 strcat(oFileRsrc, fname);
1178
1179                 if ((ofile = open(oFileRsrc, O_RDONLY, 0)) < 0) {
1180                         fprintf(stderr, "%s: cannot read finderinfo: %s\n",
1181                             name, strerror(errno));
1182                         skipfile();
1183                         return (FAIL);
1184                 }
1185                 read(ofile, buf, 70);
1186                 (void) close(ofile);
1187                 p = buf;
1188                 hp = (ASDHeaderPtr)p;
1189                 /* the header */
1190                 hp->entries++;
1191                 p += sizeof(ASDHeader) - CORRECT;
1192                 ep = (ASDEntryPtr)p;
1193                 /* the finderinfo entry */
1194                 ep->offset += sizeof(ASDEntry);
1195                 loff = ep->offset;
1196
1197                 p += sizeof(ASDEntry);
1198                 /* the finderinfo data */
1199                 bcopy(p, p + sizeof(ASDEntry), INFOLEN);
1200                 ep = (ASDEntryPtr)p;
1201                 /* the new resourcefork entry */
1202                 ep->entryID = EntryRSRCFork;
1203                 ep->offset = loff + INFOLEN;
1204                 ep->len = di_size;
1205                 /* write the new appledouble entries to the file */
1206                 if ((ofile = open(oFileRsrc, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
1207                         fprintf(stderr, "%s: cannot create resource file: %s\n",
1208                             name, strerror(errno));
1209                         skipfile();
1210                         return (FAIL);
1211                 }
1212                 write(ofile, buf, 70 + sizeof(ASDEntry));
1213                 /* and add the resource data from tape */
1214                 getfile(xtrfile, xtrskip);
1215
1216                 (void) fchown(ofile, uid, gid);
1217                 (void) fchmod(ofile, mode);
1218                 (void) close(ofile);
1219                 utimes(oFileRsrc, timep);
1220                 (void) lsetflags(oFileRsrc, flags);
1221                 return (GOOD);
1222         }
1223         /* NOTREACHED */
1224 }
1225 #endif /* DUMP_MACOSX */
1226
1227 int
1228 readxattr(char *buffer)
1229 {
1230         if (dflag)
1231                 msg("reading EA data for inode %lu\n", curfile.ino);
1232
1233         curfile.name = "EA block";
1234         if (curfile.dip->di_size > XATTR_MAXSIZE) {
1235                 fprintf(stderr, "EA size too big (%ld)", (long)curfile.dip->di_size);
1236                 skipfile();
1237                 return (FAIL);
1238         }
1239         
1240         memset(xattrbuf, 0, XATTR_MAXSIZE);
1241         xattrlen = 0;
1242
1243         getfile(xtrxattr, xtrnull);
1244
1245         memcpy(buffer, xattrbuf, XATTR_MAXSIZE);
1246
1247         return (GOOD);
1248 }
1249
1250 /*
1251  * skip over bit maps on the tape
1252  */
1253 void
1254 skipmaps(void)
1255 {
1256
1257         while (spcl.c_type == TS_BITS || spcl.c_type == TS_CLRI)
1258                 skipfile();
1259 }
1260
1261 /*
1262  * skip over a file on the tape
1263  */
1264 void
1265 skipfile(void)
1266 {
1267
1268         curfile.action = SKIP;
1269         getfile(xtrnull, xtrnull);
1270 }
1271
1272 /*
1273  * skip over any extended attributes.
1274  */
1275 void
1276 skipxattr(void)
1277 {
1278
1279         while (spcl.c_flags & DR_EXTATTRIBUTES)
1280                 skipfile();
1281 }
1282
1283 /*
1284  * Extract a file from the tape.
1285  * When an allocated block is found it is passed to the fill function;
1286  * when an unallocated block (hole) is found, a zeroed buffer is passed
1287  * to the skip function.
1288  */
1289 void
1290 getfile(void (*fill) __P((char *, size_t)), void (*skip) __P((char *, size_t)))
1291 {
1292         int i;
1293         volatile int curblk = 0;
1294         volatile quad_t size = spcl.c_dinode.di_size;
1295         volatile int last_write_was_hole = 0;
1296         quad_t origsize = size;
1297         static char clearedbuf[MAXBSIZE];
1298         char buf[MAXBSIZE / TP_BSIZE][TP_BSIZE];
1299         char junk[TP_BSIZE];
1300
1301         if (spcl.c_type == TS_END)
1302                 panic("ran off end of tape\n");
1303         if (spcl.c_magic != NFS_MAGIC)
1304                 panic("not at beginning of a file\n");
1305         if (!gettingfile && setjmp(restart) != 0)
1306                 return;
1307         gettingfile++;
1308 loop:
1309         for (i = 0; i < spcl.c_count; i++) {
1310                 if (readmapflag || spcl.c_addr[i]) {
1311                         readtape(&buf[curblk++][0]);
1312                         if (curblk == fssize / TP_BSIZE) {
1313                                 (*fill)((char *)buf, (size_t)(size > TP_BSIZE ?
1314                                      fssize : (curblk - 1) * TP_BSIZE + size));
1315                                 curblk = 0;
1316                                 last_write_was_hole = 0;
1317                         }
1318                 } else {
1319                         if (curblk > 0) {
1320                                 (*fill)((char *)buf, (size_t)(size > TP_BSIZE ?
1321                                      curblk * TP_BSIZE :
1322                                      (curblk - 1) * TP_BSIZE + size));
1323                                 curblk = 0;
1324                         }
1325                         (*skip)(clearedbuf, (long)(size > TP_BSIZE ?
1326                                 TP_BSIZE : size));
1327                         last_write_was_hole = 1;
1328                 }
1329                 if ((size -= TP_BSIZE) <= 0) {
1330                         for (i++; i < spcl.c_count; i++)
1331                                 if (readmapflag || spcl.c_addr[i])
1332                                         readtape(junk);
1333                         break;
1334                 }
1335         }
1336         if (gethead(&spcl) == GOOD && size > 0) {
1337                 if (spcl.c_type == TS_ADDR)
1338                         goto loop;
1339                 Dprintf(stdout,
1340                         "Missing address (header) block for %s at %ld blocks\n",
1341                         curfile.name, (long)blksread);
1342         }
1343         if (curblk > 0) {
1344                 (*fill)((char *)buf, (size_t)((curblk * TP_BSIZE) + size));
1345                 last_write_was_hole = 0;
1346         }
1347         if (size > 0) {
1348                 fprintf(stderr, "Missing blocks at the end of %s, assuming hole\n", curfile.name);
1349                 while (size > 0) {
1350                         size_t skp = size > TP_BSIZE ? TP_BSIZE : size;
1351                         (*skip)(clearedbuf, skp);
1352                         size -= skp;
1353                 }
1354                 last_write_was_hole = 1;
1355         }
1356         if (last_write_was_hole) {
1357                 FTRUNCATE(ofile, origsize);
1358         }
1359         if (!readingmaps) 
1360                 findinode(&spcl);
1361         gettingfile = 0;
1362 }
1363
1364 /*
1365  * Write out the next block of a file.
1366  */
1367 static void
1368 xtrfile(char *buf, size_t size)
1369 {
1370
1371         if (Nflag)
1372                 return;
1373         if (write(ofile, buf, (int) size) == -1)
1374                 err(1, "write error extracting inode %lu, name %s\nwrite",
1375                         (unsigned long)curfile.ino, curfile.name);
1376 }
1377
1378 #ifdef DUMP_MACOSX
1379 static void
1380 xtrfilefinderinfo(char *buf, size_t size)
1381 {
1382         bcopy(buf, &gFndrInfo, size);
1383 }
1384 #endif /* DUMP_MACOSX */
1385
1386 /*
1387  * Skip over a hole in a file.
1388  */
1389 /* ARGSUSED */
1390 static void
1391 xtrskip(UNUSED(char *buf), size_t size)
1392 {
1393
1394         if (LSEEK(ofile, (OFF_T)size, SEEK_CUR) == -1)
1395                 err(1, "seek error extracting inode %lu, name %s\nlseek",
1396                         (unsigned long)curfile.ino, curfile.name);
1397 }
1398
1399 /*
1400  * Collect the next block of a symbolic link.
1401  */
1402 static void
1403 xtrlnkfile(char *buf, size_t size)
1404 {
1405
1406         pathlen += size;
1407         if (pathlen > MAXPATHLEN) {
1408                 buf[size - 1] = '\0';
1409                 errx(1, "symbolic link name: %s->%s%s; too long %d",
1410                     curfile.name, lnkbuf, buf, pathlen);
1411         }
1412         (void) strcat(lnkbuf, buf);
1413         lnkbuf[pathlen] = '\0';
1414 }
1415
1416 /*
1417  * Skip over a hole in a symbolic link (should never happen).
1418  */
1419 /* ARGSUSED */
1420 static void
1421 xtrlnkskip(UNUSED(char *buf), UNUSED(size_t size))
1422 {
1423
1424         errx(1, "unallocated block in symbolic link %s", curfile.name);
1425 }
1426
1427 /*
1428  * Collect the next block of a bit map.
1429  */
1430 static void
1431 xtrmap(char *buf, size_t size)
1432 {
1433
1434         memmove(map, buf, size);
1435         map += size;
1436 }
1437
1438 /*
1439  * Skip over a hole in a bit map (should never happen).
1440  */
1441 /* ARGSUSED */
1442 static void
1443 xtrmapskip(UNUSED(char *buf), size_t size)
1444 {
1445
1446         panic("hole in map\n");
1447         map += size;
1448 }
1449
1450 /*
1451  * Noop, when an extraction function is not needed.
1452  */
1453 /* ARGSUSED */
1454 void
1455 xtrnull(UNUSED(char *buf), UNUSED(size_t size))
1456 {
1457
1458         return;
1459 }
1460
1461 #if COMPARE_ONTHEFLY
1462 /*
1463  * Compare the next block of a file.
1464  */
1465 static void
1466 xtrcmpfile(char *buf, size_t size)
1467 {
1468         static char cmpbuf[MAXBSIZE];
1469
1470         if (cmperror)
1471                 return;
1472         
1473         if (read(ifile, cmpbuf, size) != (ssize_t)size) {
1474                 fprintf(stderr, "%s: size has changed.\n", 
1475                         curfile.name);
1476                 cmperror = 1;
1477                 return;
1478         }
1479         
1480         if (memcmp(buf, cmpbuf, size) != 0) {
1481                 fprintf(stderr, "%s: tape and disk copies are different\n",
1482                         curfile.name);
1483                 cmperror = 1;
1484                 return;
1485         }
1486 }
1487
1488 /*
1489  * Skip over a hole in a file.
1490  */
1491 static void
1492 xtrcmpskip(UNUSED(char *buf), size_t size)
1493 {
1494         static char cmpbuf[MAXBSIZE];
1495         int i;
1496
1497         if (cmperror)
1498                 return;
1499         
1500         if (read(ifile, cmpbuf, size) != (ssize_t)size) {
1501                 fprintf(stderr, "%s: size has changed.\n", 
1502                         curfile.name);
1503                 cmperror = 1;
1504                 return;
1505         }
1506
1507         for (i = 0; i < (int)size; ++i)
1508                 if (cmpbuf[i] != '\0') {
1509                         fprintf(stderr, "%s: tape and disk copies are different\n",
1510                                 curfile.name);
1511                         cmperror = 1;
1512                         return;
1513                 }
1514 }
1515 #endif /* COMPARE_ONTHEFLY */
1516
1517 static void
1518 xtrxattr(char *buf, size_t size)
1519 {
1520         if (xattrlen + size > XATTR_MAXSIZE) {
1521                 fprintf(stderr, "EA size too big (%ld)", (long)xattrlen + size);
1522                 return;
1523         }
1524         memcpy(xattrbuf + xattrlen, buf, size);
1525         xattrlen += size;
1526 }
1527
1528 #if !COMPARE_ONTHEFLY
1529 static int
1530 do_cmpfiles(int fd_tape, int fd_disk, OFF_T size)
1531 {
1532         static char buf_tape[BUFSIZ];
1533         static char buf_disk[BUFSIZ];
1534         ssize_t n_tape;
1535         ssize_t n_disk;
1536
1537         while (size > 0) {
1538                 if ((n_tape = read(fd_tape, buf_tape, sizeof(buf_tape))) < 1) {
1539                         close(fd_tape), close(fd_disk);
1540                         panic("do_cmpfiles: unexpected EOF[1]");
1541                 }
1542                 if ((n_disk = read(fd_disk, buf_disk, sizeof(buf_tape))) < 1) {
1543                         close(fd_tape), close(fd_disk);
1544                         panic("do_cmpfiles: unexpected EOF[2]");
1545                 }
1546                 if (n_tape != n_disk) {
1547                         close(fd_tape), close(fd_disk);
1548                         panic("do_cmpfiles: sizes different!");
1549                 }
1550                 if (memcmp(buf_tape, buf_disk, (size_t)n_tape) != 0) return (1);
1551                 size -= n_tape;
1552         }
1553         return (0);
1554 }
1555
1556 /* for debugging compare problems */
1557 #undef COMPARE_FAIL_KEEP_FILE
1558
1559 static
1560 #ifdef COMPARE_FAIL_KEEP_FILE
1561 /* return true if tapefile should be unlinked after compare */
1562 int
1563 #else
1564 void
1565 #endif
1566 cmpfiles(char *tapefile, char *diskfile, struct STAT *sbuf_disk)
1567 {
1568         struct STAT sbuf_tape;
1569         int fd_tape, fd_disk;
1570
1571         if (STAT(tapefile, &sbuf_tape) != 0) {
1572                 panic("can't lstat tmp file %s: %s\n", tapefile,
1573                       strerror(errno));
1574                 do_compare_error;
1575         }
1576
1577         if (sbuf_disk->st_size != sbuf_tape.st_size) {
1578                 fprintf(stderr,
1579                         "%s: size changed from %lld to %lld.\n",
1580                         diskfile, (long long)sbuf_tape.st_size, (long long)sbuf_disk->st_size);
1581                 do_compare_error;
1582 #ifdef COMPARE_FAIL_KEEP_FILE
1583                 return (0);
1584 #else
1585                 return;
1586 #endif
1587         }
1588
1589         if ((fd_tape = OPEN(tapefile, O_RDONLY)) < 0) {
1590                 panic("can't open %s: %s\n", tapefile, strerror(errno));
1591                 do_compare_error;
1592         }
1593         if ((fd_disk = OPEN(diskfile, O_RDONLY)) < 0) {
1594                 close(fd_tape);
1595                 panic("can't open %s: %s\n", diskfile, strerror(errno));
1596                 do_compare_error;
1597         }
1598
1599         if (do_cmpfiles(fd_tape, fd_disk, sbuf_tape.st_size)) {
1600                 fprintf(stderr, "%s: tape and disk copies are different\n",
1601                         diskfile);
1602                 close(fd_tape);
1603                 close(fd_disk);
1604                 do_compare_error;
1605 #ifdef COMPARE_FAIL_KEEP_FILE
1606                 /* rename the file to live in /tmp */
1607                 /* rename `tapefile' to /tmp/<basename of diskfile> */
1608                 {
1609                         char *p = strrchr(diskfile, '/');
1610                         char newname[MAXPATHLEN];
1611                         if (!p) {
1612                                 panic("can't find / in %s\n", diskfile);
1613                         }
1614                         snprintf(newname, sizeof(newname), "%s/debug/%s", tmpdir, p + 1);
1615                         if (rename(tapefile, newname)) {
1616                                 panic("rename from %s to %s failed: %s\n",
1617                                       tapefile, newname,
1618                                       strerror(errno));
1619                         } else {
1620                                 fprintf(stderr, "*** %s saved to %s\n",
1621                                         tapefile, newname);
1622                         }
1623                 }
1624                 
1625                 /* don't unlink the file (it's not there anymore */
1626                 /* anyway) */
1627                 return (0);
1628 #else
1629                 return;
1630 #endif
1631         }
1632         close(fd_tape);
1633         close(fd_disk);
1634 #ifdef COMPARE_FAIL_KEEP_FILE
1635         return (1);
1636 #endif
1637 }
1638 #endif /* !COMPARE_ONTHEFLY */
1639
1640 static void
1641 compareattr(char *name)
1642 {
1643         int xattr_done = 0;
1644         
1645         while (spcl.c_flags & DR_EXTATTRIBUTES) {
1646                 switch (spcl.c_extattributes) {
1647                 case EXT_MACOSFNDRINFO:
1648                         msg("MacOSX not supported for comparision in this version, skipping\n");
1649                         skipfile();
1650                         break;
1651                 case EXT_MACOSRESFORK:
1652                         msg("MacOSX not supported for comparision in this version, skipping\n");
1653                         skipfile();
1654                         break;
1655                 case EXT_XATTR: {
1656                         char xattr[XATTR_MAXSIZE];
1657
1658                         if (readxattr(xattr) == GOOD) {
1659                                 if (xattr_compare(name, xattr) == FAIL)
1660                                         do_compare_error;
1661                                 xattr_done = 1;
1662                         }
1663                         else
1664                                 do_compare_error;
1665                         break;
1666                 }
1667                 default:
1668                         msg("unexpected inode extension %ld, skipping\n", spcl.c_extattributes);
1669                         skipfile();
1670                         break;
1671                 }
1672         }
1673         if (!xattr_done && xattr_compare(name, NULL) == FAIL)
1674                 do_compare_error;
1675 }
1676
1677 #if !COMPARE_ONTHEFLY
1678 static char tmpfilename[MAXPATHLEN];
1679 #endif
1680
1681 void
1682 comparefile(char *name)
1683 {
1684         mode_t mode;
1685         uid_t uid;
1686         uid_t gid;
1687         unsigned int flags;
1688         unsigned long newflags;
1689         struct STAT sb;
1690         int r;
1691 #if !COMPARE_ONTHEFLY
1692         static char *tmpfile = NULL;
1693         struct STAT stemp;
1694 #endif
1695         curfile.name = name;
1696         curfile.action = USING;
1697         mode = curfile.dip->di_mode;
1698         flags = curfile.dip->di_flags;
1699         uid = curfile.dip->di_uid;
1700         gid =  curfile.dip->di_gid;
1701
1702         if ((mode & IFMT) == IFSOCK) {
1703                 Vprintf(stdout, "skipped socket %s\n", name);
1704                 skipfile();
1705                 return;
1706         }
1707
1708         if ((r = LSTAT(name, &sb)) != 0) {
1709                 warn("unable to stat %s", name);
1710                 do_compare_error;
1711                 skipfile();
1712                 return;
1713         }
1714
1715         Vprintf(stdout, "comparing %s (size: %lld, mode: 0%o)\n", name,
1716                 (long long)sb.st_size, mode);
1717
1718         if (sb.st_mode != mode) {
1719                 fprintf(stderr, "%s: mode changed from 0%o to 0%o.\n",
1720                         name, mode & 07777, sb.st_mode & 07777);
1721                 do_compare_error;
1722         }
1723         if (sb.st_uid != uid) {
1724                 fprintf(stderr, "%s: uid changed from %d to %d.\n",
1725                         name, uid, sb.st_uid);
1726                 do_compare_error;
1727         }
1728         if (sb.st_gid != gid) {
1729                 fprintf(stderr, "%s: gid changed from %d to %d.\n",
1730                         name, gid, sb.st_gid);
1731                 do_compare_error;
1732         }
1733 #ifdef  __linux__
1734         if (lgetflags(name, &newflags) < 0) {
1735                 if (flags != 0) {
1736                         warn("%s: lgetflags failed", name);
1737                         do_compare_error;
1738                 }
1739         }
1740         else {
1741                 if (newflags != flags) {
1742                         fprintf(stderr, "%s: flags changed from 0x%08x to 0x%08lx.\n",
1743                                 name, flags, newflags);
1744                         do_compare_error;
1745                 }
1746         }
1747 #endif
1748         if (spcl.c_flags & DR_METAONLY) {
1749                 skipfile();
1750                 return;
1751         }
1752         switch (mode & IFMT) {
1753         default:
1754                 skipfile();
1755                 return;
1756
1757         case IFSOCK:
1758                 skipfile();
1759                 return;
1760
1761         case IFDIR:
1762                 skipfile();
1763                 compareattr(name);
1764                 return;
1765
1766         case IFLNK: {
1767                 char lbuf[MAXPATHLEN + 1];
1768                 int lsize;
1769
1770                 if (!(sb.st_mode & S_IFLNK)) {
1771                         fprintf(stderr, "%s: is no longer a symbolic link\n",
1772                                 name);
1773                         do_compare_error;
1774                         return;
1775                 }
1776                 lnkbuf[0] = '\0';
1777                 pathlen = 0;
1778                 getfile(xtrlnkfile, xtrlnkskip);
1779                 if (pathlen == 0) {
1780                         fprintf(stderr,
1781                                 "%s: zero length symbolic link (ignored)\n",
1782                                 name);
1783                         do_compare_error;
1784                         return;
1785                 }
1786                 if ((lsize = readlink(name, lbuf, MAXPATHLEN)) < 0) {
1787                         panic("readlink of %s failed: %s\n", name,
1788                               strerror(errno));
1789                         do_compare_error;
1790                 }
1791                 lbuf[lsize] = 0;
1792                 if (strcmp(lbuf, lnkbuf) != 0) {
1793                         fprintf(stderr,
1794                                 "%s: symbolic link changed from %s to %s.\n",
1795                                 name, lnkbuf, lbuf);
1796                         do_compare_error;
1797                         return;
1798                 }
1799                 compareattr(name);
1800                 return;
1801         }
1802
1803         case IFCHR:
1804         case IFBLK:
1805                 if (!(sb.st_mode & (S_IFCHR|S_IFBLK))) {
1806                         fprintf(stderr, "%s: no longer a special file\n",
1807                                 name);
1808                         do_compare_error;
1809                         skipfile();
1810                         return;
1811                 }
1812
1813                 if (sb.st_rdev != (dev_t)curfile.dip->di_rdev) {
1814                         fprintf(stderr,
1815                                 "%s: device changed from %d,%d to %d,%d.\n",
1816                                 name,
1817                                 major(curfile.dip->di_rdev),
1818                                 minor(curfile.dip->di_rdev),
1819                                 major(sb.st_rdev),
1820                                 minor(sb.st_rdev));
1821                         do_compare_error;
1822                 }
1823                 skipfile();
1824                 compareattr(name);
1825                 return;
1826
1827         case IFREG:
1828 #if COMPARE_ONTHEFLY
1829                 if ((ifile = OPEN(name, O_RDONLY)) < 0) {
1830                         warn("can't open %s", name);
1831                         skipfile();
1832                         do_compare_error;
1833                 }
1834                 else {
1835                         cmperror = 0;
1836                         getfile(xtrcmpfile, xtrcmpskip);
1837                         if (!cmperror) {
1838                                 char c;
1839                                 if (read(ifile, &c, 1) != 0) {
1840                                         fprintf(stderr, "%s: size has changed.\n", 
1841                                                 name);
1842                                         cmperror = 1;
1843                                 }
1844                         }
1845                         if (cmperror)
1846                                 do_compare_error;
1847                         close(ifile);
1848                 }
1849 #else
1850                 if (tmpfile == NULL) {
1851                         /* argument to mktemp() must not be in RO space: */
1852                         snprintf(tmpfilename, sizeof(tmpfilename), "%s/restoreCXXXXXX", tmpdir);
1853                         tmpfile = mktemp(&tmpfilename[0]);
1854                 }
1855                 if ((STAT(tmpfile, &stemp) == 0) && (unlink(tmpfile) != 0)) {
1856                         panic("cannot delete tmp file %s: %s\n",
1857                               tmpfile, strerror(errno));
1858                 }
1859                 if ((ofile = OPEN(tmpfile, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
1860                         panic("cannot create file temp file %s: %s\n",
1861                               name, strerror(errno));
1862                 }
1863                 getfile(xtrfile, xtrskip);
1864                 (void) close(ofile);
1865 #ifdef COMPARE_FAIL_KEEP_FILE
1866                 if (cmpfiles(tmpfile, name, &sb))
1867                         unlink(tmpfile);
1868 #else
1869                 cmpfiles(tmpfile, name, &sb);
1870                 unlink(tmpfile);
1871 #endif
1872 #endif /* COMPARE_ONTHEFLY */
1873                 compareattr(name);
1874                 return;
1875         }
1876         /* NOTREACHED */
1877 }
1878
1879 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
1880 static void (*readtape_func)(char *) = readtape_set;
1881
1882 /*
1883  * Read TP_BSIZE blocks from the input.
1884  * Handle read errors, and end of media.
1885  * Decompress compressed blocks.
1886  */
1887 static void
1888 readtape(char *buf)
1889 {
1890         (*readtape_func)(buf);  /* call the actual processing routine */
1891 }
1892
1893 /*
1894  * Set function pointer for readtape() routine. zflag and magtapein must
1895  * be correctly set before the first call to readtape().
1896  */
1897 static void
1898 readtape_set(char *buf)
1899 {
1900         if (!zflag) 
1901                 readtape_func = readtape_uncompr;
1902         else {
1903                 newcomprbuf(ntrec);
1904                 if (magtapein)
1905                         readtape_func = readtape_comprtape;
1906                 else
1907                         readtape_func = readtape_comprfile;
1908         }
1909         readtape(buf);
1910 }
1911
1912 #endif /* HAVE_ZLIB || HAVE_BZLIB || HAVE_LZO */
1913
1914 /*
1915  * This is the original readtape(), it's used for reading uncompressed input.
1916  * Read TP_BSIZE blocks from the input.
1917  * Handle read errors, and end of media.
1918  */
1919 static void
1920 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
1921 readtape_uncompr(char *buf)
1922 #else
1923 readtape(char *buf)
1924 #endif
1925 {
1926         ssize_t rd, newvol, i;
1927         int cnt, seek_failed;
1928
1929         if (blkcnt < numtrec) {
1930                 memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
1931                 blksread++;
1932                 tpblksread++;
1933                 return;
1934         }
1935         tbufptr = tapebuf;
1936         for (i = 0; i < ntrec; i++)
1937                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1938         if (numtrec == 0)
1939                 numtrec = ntrec;
1940         cnt = ntrec * TP_BSIZE;
1941         rd = 0;
1942 #ifdef USE_QFA
1943         if (createtapeposflag)
1944                 (void)GetTapePos(&curtapepos);
1945 #endif
1946 getmore:
1947 #ifdef RRESTORE
1948         if (!Afile && host)
1949                 i = rmtread(&tapebuf[rd], cnt);
1950         else
1951 #endif
1952                 i = read(mt, &tapebuf[rd], cnt);
1953
1954         /*
1955          * Check for mid-tape short read error.
1956          * If found, skip rest of buffer and start with the next.
1957          */
1958         if (!pipein && numtrec < ntrec && i > 0) {
1959                 Dprintf(stdout, "mid-media short read error.\n");
1960                 numtrec = ntrec;
1961         }
1962         /*
1963          * Handle partial block read.
1964          */
1965         if (pipein && i == 0 && rd > 0)
1966                 i = rd;
1967         else if (i > 0 && i != ntrec * TP_BSIZE) {
1968                 if (pipein) {
1969                         rd += i;
1970                         cnt -= i;
1971                         if (cnt > 0)
1972                                 goto getmore;
1973                         i = rd;
1974                 } else {
1975                         /*
1976                          * Short read. Process the blocks read.
1977                          */
1978                         if (i % TP_BSIZE != 0)
1979                                 Vprintf(stdout,
1980                                     "partial block read: %ld should be %ld\n",
1981                                     (long)i, ntrec * TP_BSIZE);
1982                         numtrec = i / TP_BSIZE;
1983                 }
1984         }
1985         /*
1986          * Handle read error.
1987          */
1988         if (i < 0) {
1989                 fprintf(stderr, "Tape read error while ");
1990                 switch (curfile.action) {
1991                 default:
1992                         fprintf(stderr, "trying to set up tape\n");
1993                         break;
1994                 case UNKNOWN:
1995                         fprintf(stderr, "trying to resynchronize\n");
1996                         break;
1997                 case USING:
1998                         fprintf(stderr, "restoring %s\n", curfile.name);
1999                         break;
2000                 case SKIP:
2001                         fprintf(stderr, "skipping over inode %lu\n",
2002                                 (unsigned long)curfile.ino);
2003                         break;
2004                 }
2005                 if (!yflag && !reply("continue"))
2006                         exit(1);
2007                 i = ntrec * TP_BSIZE;
2008                 memset(tapebuf, 0, (size_t)i);
2009 #ifdef RRESTORE
2010                 if (!Afile && host)
2011                         seek_failed = (rmtseek(i, 1) < 0);
2012                 else
2013 #endif
2014                         seek_failed = (LSEEK(mt, i, SEEK_CUR) == (OFF_T)-1);
2015
2016                 if (seek_failed) {
2017                         warn("continuation failed");
2018                         if (!yflag && !reply("assume end-of-tape and continue"))
2019                                 exit(1);
2020                         i = 0;
2021                 }
2022         }
2023         /*
2024          * Handle end of tape.
2025          */
2026         if (i == 0) {
2027                 Vprintf(stdout, "End-of-tape encountered\n");
2028                 if (!pipein) {
2029                         newvol = volno + 1;
2030                         volno = 0;
2031                         numtrec = 0;
2032                         getvol(newvol);
2033                         readtape(buf);
2034                         return;
2035                 }
2036                 if (rd % TP_BSIZE != 0)
2037                         panic("partial block read: %d should be %d\n",
2038                                 rd, ntrec * TP_BSIZE);
2039                 terminateinput();
2040                 memmove(&tapebuf[rd], &endoftapemark, TP_BSIZE);
2041         }
2042         blkcnt = 0;
2043         memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
2044         blksread++;
2045         tpblksread++;
2046 }
2047
2048 #if defined(HAVE_ZLIB) || defined(HAVE_BZLIB) || defined(HAVE_LZO)
2049
2050 /*
2051  * Read a compressed format block from a file or pipe and uncompress it.
2052  * Attempt to handle read errors, and end of file. 
2053  */
2054 static void
2055 readtape_comprfile(char *buf)
2056 {
2057         long rl, size, i, ret;
2058         int newvol; 
2059         struct tapebuf *tpb;
2060
2061         if (blkcnt < numtrec) {
2062                 memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
2063                 blksread++;
2064                 tpblksread++;
2065                 return;
2066         }
2067         /* need to read the next block */
2068         tbufptr = tapebuf;
2069         for (i = 0; i < ntrec; i++)
2070                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
2071         numtrec = ntrec;
2072         tpb = (struct tapebuf *) tapebuf;
2073
2074         /* read the block prefix */
2075         ret = read_a_block(mt, tapebuf, PREFIXSIZE, &rl);
2076         converttapebuf(tpb);
2077
2078         if (Vflag && (ret == 0 || rl < (int)PREFIXSIZE  ||  tpb->length == 0))
2079                 ret = 0;
2080         if (ret <= 0)
2081                 goto readerr;
2082
2083         /* read the data */
2084         size = tpb->length;
2085         if (size > bufsize)  {
2086                 /* something's wrong */
2087                 Vprintf(stdout, "Prefix size error, max size %d, got %ld\n",
2088                         bufsize, size);
2089                 size = bufsize;
2090                 tpb->length = bufsize;
2091         }
2092         ret = read_a_block(mt, tpb->buf, size, &rl);
2093         if (ret <= 0)
2094                 goto readerr;
2095
2096         tbufptr = decompress_tapebuf(tpb, rl + PREFIXSIZE);
2097         if (tbufptr == NULL) {
2098                 msg_read_error("File decompression error while");
2099                 if (!yflag && !reply("continue"))
2100                         exit(1);
2101                 memset(tapebuf, 0, bufsize);
2102                 tbufptr = tapebuf;
2103         }
2104
2105         blkcnt = 0;
2106         memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
2107         blksread++;
2108         tpblksread++;
2109         return;
2110
2111 readerr:
2112         /* Errors while reading from a file or pipe are catastrophic. Since
2113          * there are no block boundaries, it's impossible to bypass the
2114          * block in error and find the start of the next block.
2115          */
2116         if (ret == 0) {
2117                 /* It's possible to have multiple input files using -M
2118                  * and -f file1,file2...
2119                  */
2120                 Vprintf(stdout, "End-of-File encountered\n");
2121                 if (!pipein) {
2122                         newvol = volno + 1;
2123                         volno = 0;
2124                         numtrec = 0;
2125                         getvol(newvol);
2126                         readtape(buf);
2127                         return;
2128                 }
2129         }
2130         msg_read_error("Read error while");
2131         /* if (!yflag && !reply("continue")) */
2132                 exit(1);
2133 }
2134
2135 /*
2136  * Read compressed data from a tape and uncompress it.
2137  * Handle read errors, and end of media.
2138  * Since a tape consists of separate physical blocks, we try
2139  * to recover from errors by repositioning the tape to the next
2140  * block.
2141  */
2142 static void
2143 readtape_comprtape(char *buf)
2144 {
2145         long rl, size, i;
2146         int ret, newvol;
2147         struct tapebuf *tpb;
2148         struct mtop tcom;
2149
2150         if (blkcnt < numtrec) {
2151                 memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
2152                 blksread++;
2153                 tpblksread++;
2154                 return;
2155         }
2156         /* need to read the next block */
2157         tbufptr = tapebuf;
2158         for (i = 0; i < ntrec; i++)
2159                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
2160         numtrec = ntrec;
2161         tpb = (struct tapebuf *) tapebuf;
2162
2163         /* read the block */
2164         size = bufsize + PREFIXSIZE;
2165         ret = read_a_block(mt, tapebuf, size, &rl);
2166         if (ret <= 0)
2167                 goto readerr;
2168
2169         converttapebuf(tpb);
2170         tbufptr = decompress_tapebuf(tpb, rl);
2171         if (tbufptr == NULL) {
2172                 msg_read_error("Tape decompression error while");
2173                 if (!yflag && !reply("continue"))
2174                         exit(1);
2175                 memset(tapebuf, 0, PREFIXSIZE + bufsize);
2176                 tbufptr = tapebuf;
2177         }
2178         goto moverecord;
2179
2180 readerr:
2181         /* Handle errors: EOT switches to the next volume, other errors
2182          * attempt to position the tape to the next block.
2183          */
2184         if (ret == 0) {
2185                 Vprintf(stdout, "End-of-tape encountered\n");
2186                 newvol = volno + 1;
2187                 volno = 0;
2188                 numtrec = 0;
2189                 getvol(newvol);
2190                 readtape(buf);
2191                 return;
2192         }
2193
2194         msg_read_error("Tape read error while");
2195         if (!yflag && !reply("continue"))
2196                 exit(1);
2197         memset(tapebuf, 0, PREFIXSIZE + bufsize);
2198         tbufptr = tapebuf;
2199
2200 #ifdef RRESTORE
2201         if (host)
2202                 rl = rmtioctl(MTFSR, 1);
2203         else
2204 #endif
2205         {
2206                 tcom.mt_op = MTFSR;
2207                 tcom.mt_count = 1;
2208                 rl = ioctl(mt, MTIOCTOP, &tcom);
2209         }
2210
2211         if (rl < 0) {
2212                 warn("continuation failed");
2213                 if (!yflag && !reply("assume end-of-tape and continue"))
2214                         exit(1);
2215                 ret = 0;         /* end of tape */
2216                 goto readerr;
2217         }
2218
2219 moverecord:
2220         blkcnt = 0;
2221         memmove(buf, &tbufptr[(blkcnt++ * TP_BSIZE)], TP_BSIZE);
2222         blksread++;
2223         tpblksread++;
2224 }
2225
2226 /*
2227  *  Decompress a struct tapebuf into a buffer. readsize is the size read
2228  *  from the tape/file and is used for error messages. Returns a pointer
2229  *  to the location of the uncompressed buffer or NULL on errors.
2230  *  Adjust numtrec and complain for a short block.
2231  */
2232 static char *
2233 decompress_tapebuf(struct tapebuf *tpbin, int readsize)
2234 {
2235         /* If zflag is on, all blocks have a struct tapebuf prefix */
2236         /* zflag gets set in setup() from the dump header          */
2237         int cresult, blocklen;        
2238         unsigned long worklen;
2239         char *output = NULL,*reason = NULL, *lengtherr = NULL;              
2240        
2241         /* build a length error message */
2242         blocklen = tpbin->length;
2243         if (readsize < blocklen + (int)PREFIXSIZE)
2244                 lengtherr = "short";
2245         else
2246                 if (readsize > blocklen + (int)PREFIXSIZE)
2247                         lengtherr = "long";
2248
2249         worklen = comprlen;
2250         cresult = 1;
2251         if (tpbin->compressed) {
2252                 /* uncompress whatever we read, if it fails, complain later */
2253                 if (tpbin->flags == COMPRESS_ZLIB) {
2254 #ifndef HAVE_ZLIB
2255                         errx(1,"This restore version doesn't support zlib decompression");
2256 #else
2257                         cresult = uncompress(comprbuf, &worklen, 
2258                                              tpbin->buf, blocklen);
2259                         output = comprbuf;
2260                         switch (cresult) {
2261                                 case Z_OK:
2262                                         break;
2263                                 case Z_MEM_ERROR:
2264                                         reason = "not enough memory";
2265                                         break;
2266                                 case Z_BUF_ERROR:
2267                                         reason = "buffer too small";
2268                                         break;
2269                                 case Z_DATA_ERROR:
2270                                         reason = "data error";
2271                                         break;
2272                                 default:
2273                                         reason = "unknown";
2274                         }
2275                         if (cresult == Z_OK)
2276                                 cresult = 1;
2277                         else
2278                                 cresult = 0;
2279 #endif /* HAVE_ZLIB */
2280                 }
2281                 if (tpbin->flags == COMPRESS_BZLIB) {
2282 #ifndef HAVE_BZLIB
2283                         errx(1,"This restore version doesn't support bzlib decompression");
2284 #else
2285                         unsigned int worklen2 = worklen;
2286                         cresult = BZ2_bzBuffToBuffDecompress(
2287                                         comprbuf, &worklen2, 
2288                                         tpbin->buf, blocklen, 0, 0);
2289                         worklen = worklen2;
2290                         output = comprbuf;
2291                         switch (cresult) {
2292                                 case BZ_OK:
2293                                         break;
2294                                 case BZ_MEM_ERROR:
2295                                         reason = "not enough memory";
2296                                         break;
2297                                 case BZ_OUTBUFF_FULL:
2298                                         reason = "buffer too small";
2299                                         break;
2300                                 case BZ_DATA_ERROR:
2301                                 case BZ_DATA_ERROR_MAGIC:
2302                                 case BZ_UNEXPECTED_EOF:
2303                                         reason = "data error";
2304                                         break;
2305                                 default:
2306                                         reason = "unknown";
2307                         }
2308                         if (cresult == BZ_OK)
2309                                 cresult = 1;
2310                         else
2311                                 cresult = 0;
2312 #endif /* HAVE_BZLIB */
2313                 }
2314                 if (tpbin->flags == COMPRESS_LZO) {
2315 #ifndef HAVE_LZO
2316                         errx(1,"This restore version doesn't support lzo decompression");
2317 #else
2318                         lzo_uint worklen2 = worklen;
2319                         cresult = lzo1x_decompress(tpbin->buf, blocklen,
2320                                                    comprbuf, &worklen2, NULL);
2321                         worklen = worklen2;
2322                         output = comprbuf;
2323                         switch (cresult) {
2324                                 case LZO_E_OK:
2325                                         break;
2326                                 case LZO_E_ERROR:
2327                                 case LZO_E_EOF_NOT_FOUND:
2328                                         reason = "data error";
2329                                         break;
2330                                 default:
2331                                         reason = "unknown";
2332                         }
2333                         if (cresult == LZO_E_OK)
2334                                 cresult = 1;
2335                         else
2336                                 cresult = 0;
2337 #endif /* HAVE_LZO */
2338                 }
2339         }
2340         else {
2341                 output = tpbin->buf;
2342                 worklen = blocklen;
2343         }
2344         if (cresult) {
2345                 numtrec = worklen / TP_BSIZE;
2346                 if (worklen % TP_BSIZE != 0)
2347                         reason = "length mismatch";
2348         }
2349         if (reason) {
2350                 if (lengtherr)
2351                         fprintf(stderr, "%s compressed block: %d expected: %u\n",
2352                                 lengtherr, readsize, tpbin->length + PREFIXSIZE);
2353                 fprintf(stderr, "decompression error, block %ld: %s\n",
2354                         tpblksread+1, reason);
2355                 if (!cresult)
2356                         output = NULL;
2357         }
2358         return output;
2359 }
2360
2361 /*
2362  * Print an error message for a read error.
2363  * This was exteracted from the original readtape().
2364  */
2365 static void
2366 msg_read_error(char *m)
2367 {
2368         switch (curfile.action) {
2369                 default:
2370                         fprintf(stderr, "%s trying to set up tape\n", m);
2371                         break;
2372                 case UNKNOWN:
2373                         fprintf(stderr, "%s trying to resynchronize\n", m);
2374                         break;
2375                 case USING:
2376                         fprintf(stderr, "%s restoring %s\n", m, curfile.name);
2377                         break;
2378                 case SKIP:
2379                         fprintf(stderr, "%s skipping over inode %lu\n", m,
2380                                 (unsigned long)curfile.ino);
2381                         break;
2382         }
2383 }
2384 #endif /* HAVE_ZLIB || HAVE_BZLIB || HAVE_LZO */
2385
2386 /*
2387  * Read the first block and get the blocksize from it. Test
2388  * for a compressed dump tape/file. setup() will make the final
2389  * determination by checking the compressed flag if gethead()
2390  * finds a valid header. The test here is necessary to offset the buffer
2391  * by the size of the compressed prefix. zflag is set here so that
2392  * readtape_set can set the correct function pointer for readtape().
2393  * Note that the first block of each tape/file is not compressed
2394  * and does not have a prefix.
2395  */ 
2396 static void
2397 findtapeblksize(void)
2398 {
2399         long i;
2400         size_t len;
2401         struct tapebuf *tpb = (struct tapebuf *) tapebuf;
2402         struct s_spcl spclpt;
2403
2404         for (i = 0; i < ntrec; i++)
2405                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
2406         blkcnt = 0;
2407         tbufptr = tapebuf;
2408         /*
2409          * For a pipe or file, read in the first record. For a tape, read
2410          * the first block.
2411          */
2412         len = magtapein ? ntrec * TP_BSIZE : TP_BSIZE;
2413
2414         if (read_a_block(mt, tapebuf, len, &i) <= 0)
2415                 errx(1, "Tape read error on first record");
2416
2417         memcpy(&spclpt, tapebuf, TP_BSIZE);
2418         cvtflag = 0;
2419         if (converthead(&spclpt) == FAIL) {
2420                 cvtflag++;
2421                 if (converthead(&spclpt) == FAIL) {
2422                         /* Special case for old compressed tapes with prefix */
2423                         if (magtapein && (i % TP_BSIZE != 0)) 
2424                                 goto oldformat;
2425                         errx(1, "Tape is not a dump tape");
2426                 }
2427                 fprintf(stderr, "Converting to new file system format.\n");
2428         }
2429         /*
2430          * If the input is from a file or a pipe, we read TP_BSIZE
2431          * bytes looking for a dump header. If the dump is compressed
2432          * we need to read in the rest of the block, as determined
2433          * by c_ntrec in the dump header. The first block of the
2434          * dump is not compressed and does not have a prefix.
2435          */
2436         if (!magtapein) {
2437                 if (spclpt.c_type == TS_TAPE
2438                     && spclpt.c_flags & DR_COMPRESSED) {
2439                         /* It's a compressed dump file, read in the */
2440                         /* rest of the block based on spclpt.c_ntrec. */
2441                         if (spclpt.c_ntrec > ntrec)
2442                                 errx(1, "Tape blocksize is too large, use "
2443                                      "\'-b %d\' ", spclpt.c_ntrec);
2444                         ntrec = spclpt.c_ntrec;
2445                         len = (ntrec - 1) * TP_BSIZE;
2446                         zflag = 1;   
2447                 }
2448                 else {
2449                         /* read in the rest of the block based on bufsize */
2450                         len = bufsize - TP_BSIZE;
2451                 }
2452                 if (read_a_block(mt, tapebuf+TP_BSIZE, len, &i) < 0
2453                     || (i != (long)len && i % TP_BSIZE != 0))
2454                         errx(1,"Error reading dump file header");
2455                 tbufptr = tapebuf;
2456                 numtrec = ntrec;
2457                 Vprintf(stdout, "Input block size is %ld\n", ntrec);
2458                 return;
2459         } /* if (!magtapein) */
2460
2461         /*
2462          * If the input is a tape, we tried to read ntrec * TP_BSIZE bytes.
2463          * If the value of ntrec is too large, we read less than
2464          * what we asked for; adjust the value of ntrec and test for 
2465          * a compressed dump tape.
2466          */
2467         if (i % TP_BSIZE != 0) {
2468 oldformat:
2469                 /* may be old format compressed dump tape with a prefix */
2470                 memcpy(&spclpt, tpb->buf, TP_BSIZE);
2471                 cvtflag = 0;
2472                 if (converthead(&spclpt) == FAIL) {
2473                         cvtflag++;
2474                         if (converthead(&spclpt) == FAIL)
2475                                 errx(1, "Tape is not a dump tape");
2476                         fprintf(stderr, "Converting to new file system format.\n");
2477                 }
2478                 if (i % TP_BSIZE == PREFIXSIZE
2479                     && tpb->compressed == 0
2480                     && spclpt.c_type == TS_TAPE
2481                     && spclpt.c_flags & DR_COMPRESSED) {
2482                         zflag = 1;
2483                         tbufptr = tpb->buf;
2484                         if (tpb->length > bufsize)
2485                                 errx(1, "Tape blocksize is too large, use "
2486                                         "\'-b %d\' ", tpb->length / TP_BSIZE);
2487                 }
2488                 else
2489                         errx(1, "Tape block size (%ld) is not a multiple of dump block size (%d)",
2490                                 i, TP_BSIZE);
2491         }
2492         ntrec = i / TP_BSIZE;
2493         if (spclpt.c_type == TS_TAPE) {
2494                 if (spclpt.c_flags & DR_COMPRESSED)
2495                         zflag = 1;
2496                 if (spclpt.c_ntrec > ntrec)
2497                         errx(1, "Tape blocksize is too large, use "
2498                                 "\'-b %d\' ", spclpt.c_ntrec);
2499         }
2500         numtrec = ntrec;
2501         Vprintf(stdout, "Tape block size is %ld\n", ntrec);
2502 }
2503
2504 /*
2505  * Read a block of data handling all of the messy details.
2506  */
2507 static int read_a_block(int fd, char *buf, size_t len, long *lengthread)
2508 {
2509         long i = 1, size;
2510
2511         size = len;
2512         while (size > 0) {
2513 #ifdef RRESTORE
2514                 if (!Afile && host)
2515                         i = rmtread(buf, size);
2516                 else
2517 #endif
2518                         i = read(fd, buf, size);                 
2519
2520                 if (i <= 0)
2521                         break; /* EOD or error */
2522                 size -= i;
2523                 if (magtapein)
2524                         break; /* block at a time for mt */
2525                 buf += i;
2526         }
2527         *lengthread = len - size;
2528         return i;
2529 }
2530
2531 void
2532 closemt(void)
2533 {
2534
2535         if (mt < 0)
2536                 return;
2537 #ifdef RRESTORE
2538         if (!Afile && host)
2539                 rmtclose();
2540         else
2541 #endif
2542                 (void) close(mt);
2543 }
2544
2545 static void
2546 setmagtapein(void) {
2547         struct mtget mt_stat;
2548         static int done = 0;
2549         if (done)
2550                 return;
2551         done = 1;
2552         if (!pipein) {
2553                 /* need to know if input is really from a tape */
2554 #ifdef RRESTORE
2555                 if (host)
2556                         magtapein = !lflag;
2557                 else
2558 #endif
2559                         magtapein = ioctl(mt, MTIOCGET, (char *)&mt_stat) == 0;
2560         }
2561
2562         Vprintf(stdout,"Input is from a %s %s\n",
2563                         host ? "remote" : "local",
2564                         magtapein ? "tape" :
2565                         Vflag ? "multi-volume (no tape)" : "file/pipe");
2566 }
2567
2568 /*
2569  * Read the next block from the tape.
2570  * Check to see if it is one of several vintage headers.
2571  * If it is an old style header, convert it to a new style header.
2572  * If it is not any valid header, return an error.
2573  */
2574 static int
2575 gethead(struct s_spcl *buf)
2576 {
2577         readtape((char *)buf);
2578         return converthead(buf);
2579 }
2580
2581 static int
2582 converthead(struct s_spcl *buf)
2583 {
2584         int32_t i;
2585         union {
2586                 quad_t  qval;
2587                 int32_t val[2];
2588         } qcvt;
2589         union u_ospcl {
2590                 char dummy[TP_BSIZE];
2591                 struct  s_ospcl {
2592                         int32_t c_type;
2593                         int32_t c_date;
2594                         int32_t c_ddate;
2595                         int32_t c_volume;
2596                         int32_t c_tapea;
2597                         u_int16_t c_inumber;
2598                         int32_t c_magic;
2599                         int32_t c_checksum;
2600                         struct odinode {
2601                                 u_int16_t odi_mode;
2602                                 u_int16_t odi_nlink;
2603                                 u_int16_t odi_uid;
2604                                 u_int16_t odi_gid;
2605                                 int32_t odi_size;
2606                                 int32_t odi_rdev;
2607                                 char    odi_addr[36];
2608                                 int32_t odi_atime;
2609                                 int32_t odi_mtime;
2610                                 int32_t odi_ctime;
2611                         } c_dinode;
2612                         int32_t c_count;
2613                         char    c_fill[256];
2614                 } s_ospcl;
2615         } u_ospcl;
2616
2617         if (!cvtflag) {
2618                 if (buf->c_magic != NFS_MAGIC) {
2619                         if (swabi(buf->c_magic) != NFS_MAGIC)
2620                                 return (FAIL);
2621                         if (!Bcvt) {
2622                                 Vprintf(stdout, "Note: Doing Byte swapping\n");
2623                                 Bcvt = 1;
2624                         }
2625                 }
2626                 if (checksum((int *)buf) == FAIL)
2627                         return (FAIL);
2628                 if (Bcvt)
2629                         swabst((u_char *)"8i4s1l29i528bi192b4i", (u_char *)buf);
2630                 goto good;
2631         }
2632         memcpy(&u_ospcl.s_ospcl, buf, TP_BSIZE);
2633         if (checksum((int *)(&u_ospcl.s_ospcl)) == FAIL)
2634                 return(FAIL);
2635         if (u_ospcl.s_ospcl.c_magic == OFS_MAGIC) {
2636                 memset((char *)buf, 0, (long)TP_BSIZE);
2637                 buf->c_type = u_ospcl.s_ospcl.c_type;
2638                 buf->c_date = u_ospcl.s_ospcl.c_date;
2639                 buf->c_ddate = u_ospcl.s_ospcl.c_ddate;
2640                 buf->c_volume = u_ospcl.s_ospcl.c_volume;
2641                 buf->c_tapea = u_ospcl.s_ospcl.c_tapea;
2642                 buf->c_inumber = u_ospcl.s_ospcl.c_inumber;
2643                 buf->c_checksum = u_ospcl.s_ospcl.c_checksum;
2644                 buf->c_magic = u_ospcl.s_ospcl.c_magic;
2645                 buf->c_dinode.di_mode = u_ospcl.s_ospcl.c_dinode.odi_mode;
2646                 buf->c_dinode.di_nlink = u_ospcl.s_ospcl.c_dinode.odi_nlink;
2647                 buf->c_dinode.di_uid = u_ospcl.s_ospcl.c_dinode.odi_uid;
2648                 buf->c_dinode.di_gid = u_ospcl.s_ospcl.c_dinode.odi_gid;
2649                 buf->c_dinode.di_size = u_ospcl.s_ospcl.c_dinode.odi_size;
2650                 buf->c_dinode.di_rdev = u_ospcl.s_ospcl.c_dinode.odi_rdev;
2651 #if defined(__linux__) || defined(sunos)
2652                 buf->c_dinode.di_atime.tv_sec = u_ospcl.s_ospcl.c_dinode.odi_atime;
2653                 buf->c_dinode.di_mtime.tv_sec = u_ospcl.s_ospcl.c_dinode.odi_mtime;
2654                 buf->c_dinode.di_ctime.tv_sec = u_ospcl.s_ospcl.c_dinode.odi_ctime;
2655 #else   /* __linux__ || sunos */
2656                 buf->c_dinode.di_atime = u_ospcl.s_ospcl.c_dinode.odi_atime;
2657                 buf->c_dinode.di_mtime = u_ospcl.s_ospcl.c_dinode.odi_mtime;
2658                 buf->c_dinode.di_ctime = u_ospcl.s_ospcl.c_dinode.odi_ctime;
2659 #endif  /* __linux__ || sunos */
2660                 buf->c_count = u_ospcl.s_ospcl.c_count;
2661                 memmove(buf->c_addr, u_ospcl.s_ospcl.c_fill, (long)256);
2662         }
2663         else if (u_ospcl.s_ospcl.c_magic == FS_UFS2_MAGIC) {
2664                 buf->c_date = (int32_t)(*(int64_t *)&u_ospcl.dummy[896]);
2665                 buf->c_ddate = (int32_t)(*(int64_t *)&u_ospcl.dummy[904]);
2666                 buf->c_tapea = (int32_t)(*(int64_t *)&u_ospcl.dummy[912]);
2667                 buf->c_firstrec = (int32_t)(*(int64_t *)&u_ospcl.dummy[920]);
2668                 buf->c_ntrec = 0;
2669                 buf->c_extattributes = 0;
2670                 buf->c_flags |= DR_NEWINODEFMT;
2671                 ufs2flag = 1;
2672         }
2673         else
2674                 return(FAIL);
2675         buf->c_magic = NFS_MAGIC;
2676
2677 good:
2678         if ((buf->c_dinode.di_size == 0 || buf->c_dinode.di_size > 0xfffffff) &&
2679             (buf->c_dinode.di_mode & IFMT) == IFDIR && Qcvt == 0) {
2680                 qcvt.qval = buf->c_dinode.di_size;
2681                 if (qcvt.val[0] || qcvt.val[1]) {
2682                         Vprintf(stdout, "Note: Doing Quad swapping\n");
2683                         Qcvt = 1;
2684                 }
2685         }
2686         if (Qcvt) {
2687                 qcvt.qval = buf->c_dinode.di_size;
2688                 i = qcvt.val[1];
2689                 qcvt.val[1] = qcvt.val[0];
2690                 qcvt.val[0] = i;
2691                 buf->c_dinode.di_size = qcvt.qval;
2692         }
2693         readmapflag = 0;
2694
2695         switch (buf->c_type) {
2696
2697         case TS_CLRI:
2698         case TS_BITS:
2699                 /*
2700                  * Have to patch up missing information in bit map headers
2701                  */
2702                 buf->c_inumber = 0;
2703                 buf->c_dinode.di_size = buf->c_count * TP_BSIZE;
2704                 if (buf->c_count > TP_NINDIR)
2705                         readmapflag = 1;
2706                 else 
2707                         for (i = 0; i < buf->c_count; i++)
2708                                 buf->c_addr[i]++;
2709                 break;
2710
2711         case TS_TAPE:
2712                 if ((buf->c_flags & DR_NEWINODEFMT) == 0)
2713                         oldinofmt = 1;
2714                 /* fall through */
2715         case TS_END:
2716                 buf->c_inumber = 0;
2717                 if (buf->c_flags & DR_INODEINFO) {
2718                         memcpy(volinfo, buf->c_inos, TP_NINOS * sizeof(dump_ino_t));
2719                         if (Bcvt)
2720                                 swabst((u_char *)"128i", (u_char *)volinfo);
2721                 }
2722                 break;
2723
2724         case TS_INODE:
2725         case TS_ADDR:
2726                 break;
2727
2728         default:
2729                 panic("gethead: unknown inode type %d\n", buf->c_type);
2730                 break;
2731         }
2732         /*
2733          * If we are restoring a filesystem with old format inodes,
2734          * copy the uid/gid to the new location.
2735          */
2736         if (oldinofmt) {
2737                 buf->c_dinode.di_uid = buf->c_dinode.di_ouid;
2738                 buf->c_dinode.di_gid = buf->c_dinode.di_ogid;
2739         }
2740         if (dflag)
2741                 accthdr(buf);
2742         return(GOOD);
2743 }
2744
2745 static void
2746 converttapebuf(struct tapebuf *tpb)
2747 {
2748         if (Bcvt) {
2749                 struct tb {
2750                         unsigned int    length:28;
2751                         unsigned int    flags:3;
2752                         unsigned int    compressed:1;
2753                 } tb;
2754                 swabst((u_char *)"i", (u_char *)tpb);
2755                 memcpy(&tb, tpb, 4);    
2756                 tpb->length = tb.length;
2757                 tpb->flags = tb.flags;
2758                 tpb->compressed = tb.compressed;
2759         }
2760 }
2761
2762 /*
2763  * Check that a header is where it belongs and predict the next header
2764  */
2765 static void
2766 accthdr(struct s_spcl *header)
2767 {
2768         static dump_ino_t previno = 0x7fffffff;
2769         static int prevtype;
2770         static long predict;
2771         long blks, i;
2772
2773         if (header->c_type == TS_TAPE) {
2774                 fprintf(stderr, "Volume header (%s inode format) ",
2775                     oldinofmt ? "old" : "new");
2776                 if (header->c_firstrec)
2777                         fprintf(stderr, "begins with record %d",
2778                                 header->c_firstrec);
2779                 fprintf(stderr, "\n");
2780                 previno = 0x7fffffff;
2781                 return;
2782         }
2783         if (previno == 0x7fffffff)
2784                 goto newcalc;
2785         switch (prevtype) {
2786         case TS_BITS:
2787                 fprintf(stderr, "Dumped inodes map header");
2788                 break;
2789         case TS_CLRI:
2790                 fprintf(stderr, "Used inodes map header");
2791                 break;
2792         case TS_INODE:
2793                 fprintf(stderr, "File header, ino %lu", (unsigned long)previno);
2794                 break;
2795         case TS_ADDR:
2796                 fprintf(stderr, "File continuation header, ino %ld", (long)previno);
2797                 break;
2798         case TS_END:
2799                 fprintf(stderr, "End of tape header");
2800                 break;
2801         }
2802         if (predict != blksread - 1)
2803                 fprintf(stderr, "; predicted %ld blocks, got %ld blocks",
2804                         predict, blksread - 1);
2805         fprintf(stderr, "\n");
2806 newcalc:
2807         blks = 0;
2808         if (header->c_type != TS_END)
2809                 for (i = 0; i < header->c_count; i++)
2810                         if (readmapflag || header->c_addr[i] != 0)
2811                                 blks++;
2812         predict = blks;
2813         blksread = 0;
2814         prevtype = header->c_type;
2815         previno = header->c_inumber;
2816 }
2817
2818 /*
2819  * Find an inode header.
2820  * Complain if had to skip, and complain is set.
2821  */
2822 static void
2823 findinode(struct s_spcl *header)
2824 {
2825         static long skipcnt = 0;
2826         long i;
2827         char buf[TP_BSIZE];
2828
2829         curfile.name = "<name unknown>";
2830         curfile.action = UNKNOWN;
2831         curfile.dip = NULL;
2832         curfile.ino = 0;
2833         do {
2834                 if (header->c_magic != NFS_MAGIC) {
2835                         skipcnt++;
2836                         while (gethead(header) == FAIL ||
2837                             header->c_date != dumpdate)
2838                                 skipcnt++;
2839                 }
2840                 switch (header->c_type) {
2841
2842                 case TS_ADDR:
2843                         /*
2844                          * Skip up to the beginning of the next record
2845                          */
2846                         for (i = 0; i < header->c_count; i++)
2847                                 if (header->c_addr[i])
2848                                         readtape(buf);
2849                         while (gethead(header) == FAIL ||
2850                             header->c_date != dumpdate)
2851                                 skipcnt++;
2852                         break;
2853
2854                 case TS_INODE:
2855                         curfile.dip = &header->c_dinode;
2856                         curfile.ino = header->c_inumber;
2857                         break;
2858
2859                 case TS_END:
2860                         curfile.ino = maxino;
2861                         break;
2862
2863                 case TS_CLRI:
2864                         curfile.name = "<file removal list>";
2865                         break;
2866
2867                 case TS_BITS:
2868                         curfile.name = "<file dump list>";
2869                         break;
2870
2871                 case TS_TAPE:
2872                         panic("unexpected tape header\n");
2873                         /* NOTREACHED */
2874
2875                 default:
2876                         panic("unknown tape header type %d\n", spcl.c_type);
2877                         /* NOTREACHED */
2878
2879                 }
2880         } while (header->c_type == TS_ADDR);
2881         if (skipcnt > 0)
2882 #ifdef USE_QFA
2883                 if (!noresyncmesg)
2884 #endif
2885                         fprintf(stderr, "resync restore, skipped %ld blocks\n",
2886                                 skipcnt);
2887         skipcnt = 0;
2888 }
2889
2890 static int
2891 checksum(int *buf)
2892 {
2893         int i, j;
2894
2895         j = sizeof(union u_spcl) / sizeof(int);
2896         i = 0;
2897         if(!Bcvt) {
2898                 do
2899                         i += *buf++;
2900                 while (--j);
2901         } else {
2902                 /* What happens if we want to read restore tapes
2903                         for a 16bit int machine??? */
2904                 do
2905                         i += swabi(*buf++);
2906                 while (--j);
2907         }
2908
2909         if (i != CHECKSUM) {
2910                 fprintf(stderr, "Checksum error %o, inode %lu file %s\n", i,
2911                         (unsigned long)curfile.ino, curfile.name);
2912                 return(FAIL);
2913         }
2914         return(GOOD);
2915 }
2916
2917 #ifdef RRESTORE
2918 #ifdef __STDC__
2919 #include <stdarg.h>
2920 #else
2921 #include <varargs.h>
2922 #endif
2923
2924 void
2925 #ifdef __STDC__
2926 msg(const char *fmt, ...)
2927 #else
2928 msg(fmt, va_alist)
2929         char *fmt;
2930         va_dcl
2931 #endif
2932 {
2933         va_list ap;
2934 #ifdef __STDC__
2935         va_start(ap, fmt);
2936 #else
2937         va_start(ap);
2938 #endif
2939         (void)vfprintf(stderr, fmt, ap);
2940         va_end(ap);
2941 }
2942 #endif /* RRESTORE */
2943
2944 static u_char *
2945 swab16(u_char *sp, int n)
2946 {
2947         char c;
2948
2949         while (--n >= 0) {
2950                 c = sp[0]; sp[0] = sp[1]; sp[1] = c;
2951                 sp += 2;
2952         }
2953         return (sp);
2954 }
2955
2956 static u_char *
2957 swab32(u_char *sp, int n)
2958 {
2959         char c;
2960
2961         while (--n >= 0) {
2962                 c = sp[0]; sp[0] = sp[3]; sp[3] = c;
2963                 c = sp[1]; sp[1] = sp[2]; sp[2] = c;
2964                 sp += 4;
2965         }
2966         return (sp);
2967 }
2968
2969 static u_char *
2970 swab64(u_char *sp, int n)
2971 {
2972         char c;
2973
2974         while (--n >= 0) {
2975                 c = sp[0]; sp[0] = sp[7]; sp[7] = c;
2976                 c = sp[1]; sp[1] = sp[6]; sp[6] = c;
2977                 c = sp[2]; sp[2] = sp[5]; sp[5] = c;
2978                 c = sp[3]; sp[3] = sp[4]; sp[4] = c;
2979                 sp += 8;
2980         }
2981         return (sp);
2982 }
2983
2984 void
2985 swabst(u_char *cp, u_char *sp)
2986 {
2987         int n = 0;
2988
2989         while (*cp) {
2990                 switch (*cp) {
2991                 case '0': case '1': case '2': case '3': case '4':
2992                 case '5': case '6': case '7': case '8': case '9':
2993                         n = (n * 10) + (*cp++ - '0');
2994                         continue;
2995
2996                 case 's': case 'w': case 'h':
2997                         if (n == 0)
2998                                 n = 1;
2999                         sp = swab16(sp, n);
3000                         break;
3001
3002                 case 'i':
3003                         if (n == 0)
3004                                 n = 1;
3005                         sp = swab32(sp, n);
3006                         break;
3007
3008                 case 'l':
3009                         if (n == 0)
3010                                 n = 1;
3011                         sp = swab64(sp, n);
3012                         break;
3013
3014                 default: /* Any other character, like 'b' counts as byte. */
3015                         if (n == 0)
3016                                 n = 1;
3017                         sp += n;
3018                         break;
3019                 }
3020                 cp++;
3021                 n = 0;
3022         }
3023 }
3024
3025 static u_int
3026 swabi(u_int x)
3027 {
3028         swabst((u_char *)"i", (u_char *)&x);
3029         return (x);
3030 }
3031
3032 #if 0
3033 static u_long
3034 swabl(u_long x)
3035 {
3036         swabst((u_char *)"l", (u_char *)&x);
3037         return (x);
3038 }
3039 #endif
3040
3041 void
3042 RequestVol(long tnum)
3043 {
3044         FLUSHTAPEBUF();
3045         getvol(tnum);
3046 }
3047
3048 #ifdef USE_QFA
3049 #ifdef sunos
3050 extern int fdsmtc;
3051
3052 struct uscsi_cmd {
3053         int     uscsi_flags;            /* read, write, etc. see below */
3054         short   uscsi_status;           /* resulting status  */
3055         short   uscsi_timeout;          /* Command Timeout */
3056         caddr_t uscsi_cdb;              /* cdb to send to target */
3057         caddr_t uscsi_bufaddr;          /* i/o source/destination */
3058         u_int   uscsi_buflen;           /* size of i/o to take place */
3059         u_int   uscsi_resid;            /* resid from i/o operation */
3060         u_char  uscsi_cdblen;           /* # of valid cdb bytes */
3061         u_char  uscsi_rqlen;            /* size of uscsi_rqbuf */
3062         u_char  uscsi_rqstatus;         /* status of request sense cmd */
3063         u_char  uscsi_rqresid;          /* resid of request sense cmd */
3064         caddr_t uscsi_rqbuf;            /* request sense buffer */
3065         void   *uscsi_reserved_5;       /* Reserved for Future Use */
3066 };
3067
3068 #define CDB_GROUP0      6       /*  6-byte cdb's */
3069 #define CDB_GROUP1      10      /* 10-byte cdb's */
3070 #define CDB_GROUP2      10      /* 10-byte cdb's */
3071 #define CDB_GROUP3      0       /* reserved */
3072 #define CDB_GROUP4      16      /* 16-byte cdb's */
3073 #define CDB_GROUP5      12      /* 12-byte cdb's */
3074 #define CDB_GROUP6      0       /* reserved */
3075 #define CDB_GROUP7      0       /* reserved */
3076
3077 #define USCSI_WRITE     0x00000 /* send data to device */
3078 #define USCSI_SILENT    0x00001 /* no error messages */
3079 #define USCSI_DIAGNOSE  0x00002 /* fail if any error occurs */
3080 #define USCSI_ISOLATE   0x00004 /* isolate from normal commands */
3081 #define USCSI_READ      0x00008 /* get data from device */
3082 #define USCSI_RESET     0x04000 /* Reset target */
3083 #define USCSI_RESET_ALL 0x08000 /* Reset all targets */
3084 #define USCSI_RQENABLE  0x10000 /* Enable Request Sense extensions */
3085
3086 #define USCSIIOC        (0x04 << 8)
3087 #define USCSICMD        (USCSIIOC|201)  /* user scsi command */
3088
3089 #define USCSI_TIMEOUT   30
3090 #define USCSI_SHORT_TIMEOUT     900
3091 #define USCSI_LONG_TIMEOUT      14000
3092
3093 #define B(s,i) ((unsigned char)((s) >> i))
3094 #define B1(s)                           ((unsigned char)(s))
3095
3096 #define MSB4(s,v) *(s)=B(v,24),(s)[1]=B(v,16), (s)[2]=B(v,8), (s)[3]=B1(v)
3097
3098
3099 int
3100 GetTapePos(long long *pos)
3101 {
3102         int                                     err = 0;
3103         struct uscsi_cmd        scmd;
3104         char                            buf[512];
3105         char                            parm[512 * 8];
3106         long                            lpos;
3107
3108         (void)memset((void *)buf, 0, sizeof(buf));
3109         (void)memset((void *)&scmd, 0, sizeof(scmd));
3110         scmd.uscsi_flags = USCSI_READ|USCSI_SILENT;
3111         scmd.uscsi_timeout = USCSI_TIMEOUT;
3112         scmd.uscsi_cdb = buf;
3113         scmd.uscsi_cdblen = CDB_GROUP1;
3114         buf[0] = 0x34;  /* read position */
3115         buf[1] = 0;
3116         (void)memset((void *)parm, 0, 512);
3117         scmd.uscsi_bufaddr = parm;
3118         scmd.uscsi_buflen = 56;
3119         if (ioctl(fdsmtc, USCSICMD, &scmd) == -1) {
3120                 err = errno;
3121                 return err;
3122         }
3123         (void)memcpy(&lpos, &parm[4], sizeof(long));
3124         *pos = lpos;
3125         return err;
3126 }
3127
3128 int
3129 GotoTapePos(long long pos)
3130 {
3131         int                                     err = 0;
3132         struct uscsi_cmd        scmd;
3133         char                            buf[512];
3134         char                            parm[512 * 8];
3135         long                            lpos = (long)pos;
3136
3137         (void)memset((void *)buf, 0, sizeof(buf));
3138         (void)memset((void *)&scmd, 0, sizeof(scmd));
3139         scmd.uscsi_flags = USCSI_WRITE|USCSI_SILENT;
3140         scmd.uscsi_timeout = 360;       /* 5 Minutes */
3141         scmd.uscsi_cdb = buf;
3142         scmd.uscsi_cdblen = CDB_GROUP1;
3143         buf[0] = 0x2b;  /* locate */
3144         buf[1] = 0;
3145         MSB4(&buf[3], lpos);
3146         (void)memset((void *)parm, 0, 512);
3147         scmd.uscsi_bufaddr = NULL;
3148         scmd.uscsi_buflen = 0;
3149         if (ioctl(fdsmtc, USCSICMD, &scmd) == -1) {
3150                 err = errno;
3151                 return err;
3152         }
3153         return err;
3154 }
3155 #endif
3156
3157 #define LSEEK_GET_TAPEPOS       10
3158 #define LSEEK_GO2_TAPEPOS       11
3159
3160 #ifdef  __linux__
3161 typedef struct mt_pos {
3162         short    mt_op;
3163         int      mt_count;
3164 } MTPosRec, *MTPosPtr;
3165
3166
3167 /*
3168  * get the current position of the tape
3169  */
3170 int
3171 GetTapePos(long long *pos)
3172 {
3173         int err = 0;
3174
3175 #ifdef RDUMP
3176         if (host) {
3177                 *pos = (long long) rmtseek((OFF_T)0, (int)LSEEK_GET_TAPEPOS);
3178                 err = *pos < 0;
3179         }
3180         else
3181 #endif
3182         {
3183         if (magtapein) {
3184                 long mtpos;
3185                 *pos = 0;
3186                 err = (ioctl(mt, MTIOCPOS, &mtpos) < 0);
3187                 *pos = (long long)mtpos;
3188         }
3189         else {
3190                 *pos = LSEEK(mt, 0, SEEK_CUR);
3191                 err = (*pos < 0);
3192         }
3193         }
3194         if (err) {
3195                 err = errno;
3196                 fprintf(stdout, "[%ld] error: %d (getting tapepos: %lld)\n", 
3197                         (unsigned long)getpid(), err, *pos);
3198                 return err;
3199         }
3200         return err;
3201 }
3202
3203 /*
3204  * go to specified position on tape
3205  */
3206 int
3207 GotoTapePos(long long pos)
3208 {
3209         int err = 0;
3210
3211 #ifdef RDUMP
3212         if (host)
3213                 err = (rmtseek((OFF_T)pos, (int)LSEEK_GO2_TAPEPOS) < 0);
3214         else
3215 #endif
3216         {
3217         if (magtapein) {
3218                 struct mt_pos buf;
3219                 buf.mt_op = MTSEEK;
3220                 buf.mt_count = (int) pos;
3221                 err = (ioctl(mt, MTIOCTOP, &buf) < 0);
3222         }
3223         else {
3224                 pos = LSEEK(mt, pos, SEEK_SET);
3225                 err = (pos < 0);
3226         }
3227         }
3228         if (err) {
3229                 err = errno;
3230                 fprintf(stdout, "[%ld] error: %d (setting tapepos: %lld)\n", 
3231                         (unsigned long)getpid(), err, pos);
3232                 return err;
3233         }
3234         return err;
3235 }
3236 #endif /* __linux__ */
3237
3238 /*
3239  * read next data from tape to re-sync
3240  */
3241 void
3242 ReReadFromTape(void)
3243 {
3244         FLUSHTAPEBUF();
3245         noresyncmesg = 1;
3246         if (gethead(&spcl) == FAIL) {
3247 #ifdef DEBUG_QFA
3248                 fprintf(stdout, "DEBUG 1 gethead failed\n");
3249 #endif
3250         }
3251         findinode(&spcl);
3252         noresyncmesg = 0;
3253 }
3254
3255 void
3256 ReReadInodeFromTape(dump_ino_t theino)
3257 {
3258         long    cntloop = 0;
3259
3260         FLUSHTAPEBUF();
3261         noresyncmesg = 1;
3262         do {
3263                 cntloop++;
3264                 gethead(&spcl);
3265         } while (!(spcl.c_inumber == theino && spcl.c_type == TS_INODE && spcl.c_date == dumpdate));
3266 #ifdef DEBUG_QFA
3267         fprintf(stderr, "DEBUG: %ld reads\n", cntloop);
3268         fprintf(stderr, "DEBUG: bufsize %ld\n", bufsize);
3269         fprintf(stderr, "DEBUG: ntrec %ld\n", ntrec);
3270         fprintf(stderr, "DEBUG: %ld reads\n", cntloop);
3271 #endif
3272         findinode(&spcl);
3273         noresyncmesg = 0;
3274 }
3275
3276 #ifdef sunos
3277 int
3278 OpenSMTCmt(char *themagtape)
3279 {
3280         if (GetSCSIIDFromPath(themagtape, &scsiid)) {
3281                 fprintf(stderr, "can't get SCSI-ID for %s\n", themagtape);
3282                 return -1;
3283         }
3284         if (scsiid < 0) {
3285                 fprintf(stderr, "can't get SCSI-ID for %s\n", themagtape);
3286                 return -1;
3287         }
3288         sprintf(smtcpath, "/dev/rsmtc%ld,0", scsiid);
3289         if ((fdsmtc = open(smtcpath, O_RDWR)) == -1) {
3290                 fprintf(stderr, "can't open smtc device: %s, %d\n", smtcpath, errno);
3291                 return -1;
3292         }
3293         return 0;
3294 }
3295 #endif /* sunos */
3296 #endif /* USE_QFA */