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