]> git.wh0rd.org Git - dump.git/blob - dump/main.c
Added bzip2 compression to dump.
[dump.git] / dump / main.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 <pop@noos.fr>, 1999-2000
6  *      Stelian Pop <pop@noos.fr> - AlcĂ´ve <www.alcove.fr>, 2000
7  */
8
9 /*-
10  * Copyright (c) 1980, 1991, 1993, 1994
11  *      The Regents of the University of California.  All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *      This product includes software developed by the University of
24  *      California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41
42 #ifndef lint
43 static const char rcsid[] =
44         "$Id: main.c,v 1.59 2001/08/16 15:24:21 stelian Exp $";
45 #endif /* not lint */
46
47 #include <config.h>
48 #include <compatlfs.h>
49 #include <ctype.h>
50 #include <compaterr.h>
51 #include <fcntl.h>
52 #include <fstab.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58
59 #include <sys/param.h>
60 #include <sys/time.h>
61 #include <time.h>
62 #ifdef __linux__
63 #ifdef HAVE_EXT2FS_EXT2_FS_H
64 #include <ext2fs/ext2_fs.h>
65 #else
66 #include <linux/ext2_fs.h>
67 #endif
68 #include <ext2fs/ext2fs.h>
69 #include <sys/stat.h>
70 #include <bsdcompat.h>
71 #elif defined sunos
72 #include <sys/vnode.h>
73
74 #include <ufs/inode.h>
75 #include <ufs/fs.h>
76 #else
77 #include <ufs/ufs/dinode.h>
78 #include <ufs/ffs/fs.h>
79 #endif
80
81 #include <protocols/dumprestore.h>
82
83 #include "dump.h"
84 #include "pathnames.h"
85 #include "bylabel.h"
86
87 #ifndef SBOFF
88 #define SBOFF (SBLOCK * DEV_BSIZE)
89 #endif
90
91 /*
92  * Dump maps used to describe what is to be dumped.
93  */
94 int     mapsize;        /* size of the state maps */
95 char    *usedinomap;    /* map of allocated inodes */
96 char    *dumpdirmap;    /* map of directories to be dumped */
97 char    *dumpinomap;    /* map of files to be dumped */
98
99 const char *disk;       /* name of the disk file */
100 char    tape[MAXPATHLEN];/* name of the tape file */
101 char    *tapeprefix;    /* prefix of the tape file */
102 char    *dumpdates;     /* name of the file containing dump date information*/
103 char    lastlevel;      /* dump level of previous dump */
104 char    level;          /* dump level of this dump */
105 int     bzipflag;       /* compression is done using bzlib */
106 int     uflag;          /* update flag */
107 int     Mflag;          /* multi-volume flag */
108 int     qflag;          /* quit on errors flag */
109 char    *eot_script;    /* end of volume script fiag */
110 int     diskfd;         /* disk file descriptor */
111 int     tapefd;         /* tape file descriptor */
112 int     pipeout;        /* true => output to standard output */
113 int     fifoout;        /* true => output to fifo */
114 dump_ino_t curino;      /* current inumber; used globally */
115 int     newtape;        /* new tape flag */
116 int     density;        /* density in 0.1" units */
117 long    tapesize;       /* estimated tape size, blocks */
118 long    tsize;          /* tape size in 0.1" units */
119 long    asize;          /* number of 0.1" units written on current tape */
120 int     etapes;         /* estimated number of tapes */
121 int     nonodump;       /* if set, do not honor UF_NODUMP user flags */
122 int     unlimited;      /* if set, write to end of medium */
123 int     compressed;     /* if set, dump is to be compressed */
124 long long bytes_written;/* total bytes written to tape */
125 long    uncomprblks;    /* uncompressed blocks written to tape */
126 int     notify;         /* notify operator flag */
127 int     blockswritten;  /* number of blocks written on current tape */
128 int     tapeno;         /* current tape number */
129 time_t  tstart_writing; /* when started writing the first tape block */
130 time_t  tend_writing;   /* after writing the last tape block */
131 #ifdef __linux__
132 ext2_filsys fs;
133 #else
134 struct  fs *sblock;     /* the file system super block */
135 char    sblock_buf[MAXBSIZE];
136 #endif
137 long    xferrate;       /* averaged transfer rate of all volumes */
138 long    dev_bsize;      /* block size of underlying disk device */
139 int     dev_bshift;     /* log2(dev_bsize) */
140 int     tp_bshift;      /* log2(TP_BSIZE) */
141
142 #ifdef USE_QFA
143 int     gTapeposfd;
144 char    *gTapeposfile;
145 char    gTps[255];
146 int32_t gThisDumpDate;
147 #endif /* USE_QFA */
148
149 struct  dumptime *dthead;       /* head of the list version */
150 int     nddates;                /* number of records (might be zero) */
151 int     ddates_in;              /* we have read the increment file */
152 struct  dumpdates **ddatev;     /* the arrayfied version */
153
154 int     notify = 0;     /* notify operator flag */
155 int     blockswritten = 0;      /* number of blocks written on current tape */
156 int     tapeno = 0;     /* current tape number */
157 int     density = 0;    /* density in bytes/0.1" " <- this is for hilit19 */
158 int     ntrec = NTREC;  /* # tape blocks in each tape record */
159 int     cartridge = 0;  /* Assume non-cartridge tape */
160 #ifdef USE_QFA
161 int     tapepos = 0;    /* assume no QFA tapeposition needed by user */
162 #endif /* USE_QFA */
163 int     dokerberos = 0; /* Use Kerberos authentication */
164 long    dev_bsize = 1;  /* recalculated below */
165 long    blocksperfile;  /* output blocks per file */
166 char    *host = NULL;   /* remote host (if any) */
167 int     sizest = 0;     /* return size estimate only */
168 int     compressed = 0; /* use zlib to compress the output, compress level 1-9 */
169 long long bytes_written = 0; /* total bytes written */
170 long    uncomprblks = 0;/* uncompressed blocks written */
171
172 #ifdef  __linux__
173 char    *__progname;
174 #endif
175
176 int     maxbsize = 64*1024;     /* XXX MAXBSIZE from sys/param.h */
177 static long numarg __P((const char *, long, long));
178 static void obsolete __P((int *, char **[]));
179 static void usage __P((void));
180 static void do_exclude_from_file __P((char *));
181 static void do_exclude_ino_str __P((char *));
182 static void incompat_flags __P((int, char, char));
183
184 static dump_ino_t iexclude_list[IEXCLUDE_MAXNUM];/* the inode exclude list */
185 static int iexclude_num = 0;                    /* number of elements in the list */
186
187 int
188 main(int argc, char *argv[])
189 {
190         register dump_ino_t ino;
191         register int dirty;
192         register struct dinode *dp;
193         register struct fstab *dt;
194         register char *map;
195         register int ch;
196         int i, anydirskipped;
197         int aflag = 0, bflag = 0, Tflag = 0, honorlevel = 1;
198         dump_ino_t maxino;
199         struct STAT statbuf;
200         dev_t filedev = 0;
201 #ifdef  __linux__
202         errcode_t retval;
203         char directory[MAXPATHLEN];
204         char pathname[MAXPATHLEN];
205 #endif
206         time_t tnow;
207         char *diskparam;
208
209         spcl.c_label[0] = '\0';
210         spcl.c_date = time(NULL);
211
212 #ifdef __linux__
213         __progname = argv[0];
214         directory[0] = 0;
215         initialize_ext2_error_table();
216 #endif
217
218         tsize = 0;      /* Default later, based on 'c' option for cart tapes */
219         unlimited = 1;
220         eot_script = NULL;
221         if ((tapeprefix = getenv("TAPE")) == NULL)
222                 tapeprefix = _PATH_DEFTAPE;
223         dumpdates = _PATH_DUMPDATES;
224         if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
225                 quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
226         level = '0';
227
228         if (argc < 2)
229                 usage();
230
231         obsolete(&argc, &argv);
232
233 #ifdef USE_QFA
234         gTapeposfd = -1;
235 #endif /* USE_QFA */
236
237         while ((ch = getopt(argc, argv,
238                             "0123456789aB:b:cd:e:E:f:F:h:"
239 #ifdef HAVE_BZLIB
240                             "j::"
241 #endif
242                             "L:"
243 #ifdef KERBEROS
244                             "k"
245 #endif
246                             "Mnq"
247 #ifdef USE_QFA
248                             "Q:"
249 #endif
250                             "s:ST:uWw"
251 #ifdef HAVE_ZLIB
252                             "z::"
253 #endif
254                             )) != -1)
255                 switch (ch) {
256                 /* dump level */
257                 case '0': case '1': case '2': case '3': case '4':
258                 case '5': case '6': case '7': case '8': case '9':
259                         level = ch;
260                         break;
261
262                 case 'a':               /* `auto-size', Write to EOM. */
263                         unlimited = 1;
264                         aflag = 1;
265                         break;
266
267                 case 'B':               /* blocks per output file */
268                         unlimited = 0;
269                         blocksperfile = numarg("number of blocks per file",
270                             1L, 0L);
271                         break;
272
273                 case 'b':               /* blocks per tape write */
274                         ntrec = numarg("number of blocks per write",
275                             1L, 1000L);
276                         if (ntrec > maxbsize/1024) {
277                                 msg("Please choose a blocksize <= %dkB\n",
278                                         maxbsize/1024);
279                                 msg("The ENTIRE dump is aborted.\n");
280                                 exit(X_STARTUP);
281                         }
282                         bflag = 1;
283                         break;
284
285                 case 'c':               /* Tape is cart. not 9-track */
286                         unlimited = 0;
287                         cartridge = 1;
288                         break;
289
290                 case 'd':               /* density, in bits per inch */
291                         unlimited = 0;
292                         density = numarg("density", 10L, 327670L) / 10;
293                         if (density >= 625 && !bflag)
294                                 ntrec = HIGHDENSITYTREC;
295                         break;
296                         
297                                         /* 04-Feb-00 ILC */
298                 case 'e':               /* exclude an inode */
299                         {
300                         char *p = optarg, *q;
301                         while ((q = strchr(p, ','))) {
302                                 *q = '\0';
303                                 do_exclude_ino_str(p);
304                                 p = q + 1;
305                         }
306                         do_exclude_ino_str(p);
307                         }
308                         break;
309
310                 case 'E':               /* exclude inodes read from file */
311                         do_exclude_from_file(optarg);
312                         break;
313
314                 case 'f':               /* output file */
315                         tapeprefix = optarg;
316                         break;
317
318                 case 'F':               /* end of tape script */
319                         eot_script = optarg;
320                         break;
321
322                 case 'h':
323                         honorlevel = numarg("honor level", 0L, 10L);
324                         break;
325
326 #ifdef HAVE_BZLIB
327                 case 'j':
328                         compressed = 2;
329                         bzipflag = 1;
330                         if (optarg)
331                                 compressed = numarg("compress level", 1L, 9L);
332                         break;
333 #endif /* HAVE_BZLIB */
334
335 #ifdef KERBEROS
336                 case 'k':
337                         dokerberos = 1;
338                         break;
339 #endif
340
341                 case 'L':
342                         /*
343                          * Note that although there are LBLSIZE characters,
344                          * the last must be '\0', so the limit on strlen()
345                          * is really LBLSIZE-1.
346                          */
347                         strncpy(spcl.c_label, optarg, LBLSIZE);
348                         spcl.c_label[LBLSIZE-1] = '\0';
349                         if (strlen(optarg) > LBLSIZE-1) {
350                                 msg(
351                 "WARNING Label `%s' is larger than limit of %d characters.\n",
352                                     optarg, LBLSIZE-1);
353                                 msg("WARNING: Using truncated label `%s'.\n",
354                                     spcl.c_label);
355                         }
356                         break;
357
358                 case 'M':               /* multi-volume flag */
359                         Mflag = 1;
360                         break;
361
362                 case 'n':               /* notify operators */
363                         notify = 1;
364                         break;
365
366                 case 'q':
367                         qflag = 1;
368                         break;
369
370 #ifdef USE_QFA
371                 case 'Q':               /* create tapeposfile */
372                         gTapeposfile = optarg;
373                         tapepos = 1;
374                         break;
375 #endif /* USE_QFA */
376                         
377                 case 's':               /* tape size, feet */
378                         unlimited = 0;
379                         tsize = numarg("tape size", 1L, 0L) * 12 * 10;
380                         break;
381
382                 case 'S':
383                         sizest = 1;     /* return size estimate only */
384                         break;
385
386                 case 'T':               /* time of last dump */
387                         spcl.c_ddate = unctime(optarg);
388                         if (spcl.c_ddate < 0) {
389                                 msg("bad time \"%s\"\n", optarg);
390                                 msg("The ENTIRE dump is aborted.\n");
391                                 exit(X_STARTUP);
392                         }
393                         Tflag = 1;
394                         lastlevel = '?';
395                         break;
396
397                 case 'u':               /* update dumpdates */
398                         uflag = 1;
399                         break;
400
401                 case 'W':               /* what to do */
402                 case 'w':
403                         lastdump(ch);
404                         exit(X_FINOK);  /* do nothing else */
405 #ifdef HAVE_ZLIB
406                 case 'z':
407                         compressed = 2;
408                         if (optarg)
409                                 compressed = numarg("compress level", 1L, 9L);
410                         break;
411 #endif /* HAVE_ZLIB */
412
413                 default:
414                         usage();
415                 }
416         argc -= optind;
417         argv += optind;
418
419         if (argc < 1) {
420                 msg("Must specify disk or filesystem\n");
421                 msg("The ENTIRE dump is aborted.\n");
422                 exit(X_STARTUP);
423         }
424         diskparam = *argv++;
425         if (strlen(diskparam) >= MAXPATHLEN) {
426                 msg("Disk or filesystem name too long: %s\n", diskparam);
427                 msg("The ENTIRE dump is aborted.\n");
428                 exit(X_STARTUP);
429         }
430         argc--;
431         incompat_flags(Tflag && uflag, 'T', 'u');
432         incompat_flags(aflag && blocksperfile, 'a', 'B');
433         incompat_flags(aflag && cartridge, 'a', 'c');
434         incompat_flags(aflag && density, 'a', 'd');
435         incompat_flags(aflag && tsize, 'a', 's');
436
437         if (strcmp(tapeprefix, "-") == 0) {
438                 pipeout++;
439                 tapeprefix = "standard output";
440         }
441
442         if (blocksperfile && !compressed)
443                 blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
444         else if (!unlimited) {
445                 /*
446                  * Determine how to default tape size and density
447                  *
448                  *              density                         tape size
449                  * 9-track      1600 bpi (160 bytes/.1")        2300 ft.
450                  * 9-track      6250 bpi (625 bytes/.1")        2300 ft.
451                  * cartridge    8000 bpi (100 bytes/.1")        1700 ft.
452                  *                                              (450*4 - slop)
453                  * hilit19 hits again: "
454                  */
455                 if (density == 0)
456                         density = cartridge ? 100 : 160;
457                 if (tsize == 0)
458                         tsize = cartridge ? 1700L*120L : 2300L*120L;
459         }
460
461         if (strchr(tapeprefix, ':')) {
462                 host = tapeprefix;
463                 tapeprefix = strchr(host, ':');
464                 *tapeprefix++ = '\0';
465 #ifdef RDUMP
466                 if (index(tapeprefix, '\n')) {
467                         msg("invalid characters in tape\n");
468                         msg("The ENTIRE dump is aborted.\n");
469                         exit(X_STARTUP);
470                 }
471                 if (rmthost(host) == 0)
472                         exit(X_STARTUP);
473 #else
474                 msg("remote dump not enabled\n");
475                 msg("The ENTIRE dump is aborted.\n");
476                 exit(X_STARTUP);
477 #endif
478         }
479         (void)setuid(getuid()); /* rmthost() is the only reason to be setuid */
480
481         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
482                 signal(SIGHUP, sig);
483         if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
484                 signal(SIGTRAP, sig);
485         if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
486                 signal(SIGFPE, sig);
487         if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
488                 signal(SIGBUS, sig);
489         if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
490                 signal(SIGSEGV, sig);
491         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
492                 signal(SIGTERM, sig);
493         if (signal(SIGINT, interrupt) == SIG_IGN)
494                 signal(SIGINT, SIG_IGN);
495         set_operators();        /* /etc/group snarfed */
496         getfstab();             /* /etc/fstab snarfed */
497
498         /*
499          *      disk may end in / and this can confuse
500          *      fstabsearch.
501          */
502         i = strlen(diskparam) - 1;
503         if (i > 1 && diskparam[i] == '/')
504                 diskparam[i] = '\0';
505
506         disk = get_device_name(diskparam);
507         if (!disk) {            /* null means the disk is some form
508                                    of LABEL= or UID= but it was not
509                                    found */
510                 msg("Cannot find a disk having %s\n", diskparam);
511                 msg("The ENTIRE dump is aborted.\n");
512                 exit(X_STARTUP);
513         }
514         /*
515          *      disk can be either the full special file name,
516          *      the suffix of the special file name,
517          *      the special name missing the leading '/',
518          *      the file system name with or without the leading '/'.
519          */
520         if ((dt = fstabsearch(disk)) != NULL) {
521                 /* if found then only one parameter (i.e. partition)
522                  * is allowed */
523                 if (argc >= 1) {
524                         (void)fprintf(stderr, "Unknown arguments to dump:");
525                         while (argc--)
526                                 (void)fprintf(stderr, " %s", *argv++);
527                         (void)fprintf(stderr, "\n");
528                         msg("The ENTIRE dump is aborted.\n");
529                         exit(X_STARTUP);
530                 }
531                 disk = rawname(dt->fs_spec);
532                 (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
533                 (void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
534         } else {
535 #ifdef  __linux__
536 #ifdef  HAVE_REALPATH
537                 if (realpath(disk, pathname) == NULL)
538 #endif
539                         strcpy(pathname, disk);
540                 /*
541                  * The argument could be now a mountpoint of
542                  * a filesystem specified in fstab. Search for it.
543                  */
544                 if ((dt = fstabsearch(pathname)) != NULL) {
545                         disk = rawname(dt->fs_spec);
546                         (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
547                         (void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
548                 } else {
549                         /*
550                          * The argument was not found in the fstab
551                          * assume that this is a subtree and search for it
552                          */
553                         dt = fstabsearchdir(pathname, directory);
554                         if (dt != NULL) {
555                                 char name[MAXPATHLEN];
556                                 (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
557                                 (void)snprintf(name, sizeof(name), "%s (dir %s)",
558                                               dt->fs_file, directory);
559                                 (void)strncpy(spcl.c_filesys, name, NAMELEN);
560                                 disk = rawname(dt->fs_spec);
561                         } else {
562                                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
563                                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
564                                     NAMELEN);
565                         }
566                 }
567 #else
568                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
569                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
570                     NAMELEN);
571 #endif
572         }
573
574         if (directory[0] != 0) {
575                 if (level != '0') {
576                         msg("Only level 0 dumps are allowed on a subdirectory\n");
577                         msg("The ENTIRE dump is aborted.\n");
578                         exit(X_STARTUP);
579                 }
580                 if (uflag) {
581                         msg("You can't update the dumpdates file when dumping a subdirectory\n");
582                         msg("The ENTIRE dump is aborted.\n");
583                         exit(X_STARTUP);
584                 }
585         }
586         spcl.c_dev[NAMELEN-1] = '\0';
587         spcl.c_filesys[NAMELEN-1] = '\0';
588         (void)gethostname(spcl.c_host, NAMELEN);
589         spcl.c_host[NAMELEN-1] = '\0';
590         spcl.c_level = level - '0';
591         spcl.c_type = TS_TAPE;
592         if (!Tflag)
593                 getdumptime(uflag);             /* dumpdates snarfed */
594
595         if (spcl.c_ddate == 0 && spcl.c_level) {
596                 msg("WARNING: There is no inferior level dump on this filesystem\n"); 
597                 msg("WARNING: Assuming a level 0 dump by default\n");
598                 level = '0';
599                 spcl.c_level = 0;
600         }
601
602         if (Mflag)
603                 snprintf(tape, MAXPATHLEN, "%s%03d", tapeprefix, tapeno + 1);
604         else
605                 strncpy(tape, tapeprefix, MAXPATHLEN);
606         tape[MAXPATHLEN - 1] = '\0';
607
608         if (!pipeout) {
609                 if (STAT(tape, &statbuf) != -1)
610                         fifoout= statbuf.st_mode & S_IFIFO;
611         }
612
613         if (!sizest) {
614
615                 msg("Date of this level %c dump: %s", level,
616                     ctime4(&spcl.c_date));
617 #ifdef USE_QFA
618                 gThisDumpDate = spcl.c_date;
619 #endif
620                 if (spcl.c_ddate)
621                         msg("Date of last level %c dump: %s", lastlevel,
622                             ctime4(&spcl.c_ddate));
623                 msg("Dumping %s (%s) ", disk, spcl.c_filesys);
624                 if (host)
625                         msgtail("to %s on host %s\n", tape, host);
626                 else
627                         msgtail("to %s\n", tape);
628         } /* end of size estimate */
629
630 #ifdef  __linux__
631         retval = dump_fs_open(disk, &fs);
632         if (retval) {
633                 com_err(disk, retval, "while opening filesystem");
634                 if (retval == EXT2_ET_REV_TOO_HIGH)
635                         msg("Get a newer version of dump!\n");
636                 msg("The ENTIRE dump is aborted.\n");
637                 exit(X_STARTUP);
638         }
639         if (fs->super->s_rev_level > DUMP_CURRENT_REV) {
640                 com_err(disk, retval, "while opening filesystem");
641                 msg("Get a newer version of dump!\n");
642                 msg("The ENTIRE dump is aborted.\n");
643                 exit(X_STARTUP);
644         }
645         if ((diskfd = OPEN(disk, O_RDONLY)) < 0) {
646                 msg("Cannot open %s\n", disk);
647                 msg("The ENTIRE dump is aborted.\n");
648                 exit(X_STARTUP);
649         }
650         /* if no user label specified, use ext2 filesystem label if available */
651         if (spcl.c_label[0] == '\0') {
652                 const char *lbl;
653                 if ( (lbl = get_device_label(disk)) != NULL) {
654                         strncpy(spcl.c_label, lbl, LBLSIZE);
655                         spcl.c_label[LBLSIZE-1] = '\0';
656                 }
657                 else
658                         strcpy(spcl.c_label, "none");   /* safe strcpy. */
659         }
660         sync();
661         dev_bsize = DEV_BSIZE;
662         dev_bshift = ffs(dev_bsize) - 1;
663         if (dev_bsize != (1 << dev_bshift))
664                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
665         tp_bshift = ffs(TP_BSIZE) - 1;
666         if (TP_BSIZE != (1 << tp_bshift))
667                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
668         maxino = fs->super->s_inodes_count;
669 #if     0
670         spcl.c_flags |= DR_NEWINODEFMT;
671 #endif
672 #else   /* __linux __*/
673         if ((diskfd = open(disk, O_RDONLY)) < 0) {
674                 msg("Cannot open %s\n", disk);
675                 msg("The ENTIRE dump is aborted.\n");
676                 exit(X_STARTUP);
677         }
678         sync();
679         sblock = (struct fs *)sblock_buf;
680         bread(SBOFF, (char *) sblock, SBSIZE);
681         if (sblock->fs_magic != FS_MAGIC)
682                 quit("bad sblock magic number\n");
683         dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
684         dev_bshift = ffs(dev_bsize) - 1;
685         if (dev_bsize != (1 << dev_bshift))
686                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
687         tp_bshift = ffs(TP_BSIZE) - 1;
688         if (TP_BSIZE != (1 << tp_bshift))
689                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
690 #ifdef FS_44INODEFMT
691         if (sblock->fs_inodefmt >= FS_44INODEFMT)
692                 spcl.c_flags |= DR_NEWINODEFMT;
693 #endif
694         maxino = sblock->fs_ipg * sblock->fs_ncg;
695 #endif  /* __linux__ */
696         mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
697         usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
698         dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
699         dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
700         if (usedinomap == NULL || dumpdirmap == NULL || dumpinomap == NULL)
701                 quit("out of memory allocating inode maps\n");
702         tapesize = 2 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
703
704         nonodump = spcl.c_level < honorlevel;
705
706         if (!sizest) {
707                 msg("Label: %s\n", spcl.c_label);
708
709                 if (compressed)
710                         msg("Compressing output at compression level %d (%s)\n", 
711                             compressed, bzipflag ? "bzlib" : "zlib");
712         }
713
714 #if defined(SIGINFO)
715         (void)signal(SIGINFO, statussig);
716 #endif
717
718         if (!sizest)
719                 msg("mapping (Pass I) [regular files]\n");
720 #ifdef  __linux__
721         if (directory[0] == 0)
722                 anydirskipped = mapfiles(maxino, &tapesize);
723         else {
724                 if (STAT(pathname, &statbuf) == -1) {
725                         msg("File cannot be accessed (%s).\n", pathname);
726                         msg("The ENTIRE dump is aborted.\n");
727                         exit(X_STARTUP);
728                 }
729                 filedev = statbuf.st_dev;
730                 if (!(statbuf.st_mode & S_IFDIR))       /* is a file */
731                         anydirskipped = maponefile(maxino, &tapesize, 
732                                                    directory);
733                 else
734                         anydirskipped = mapfilesfromdir(maxino, &tapesize, 
735                                                         directory);
736         }
737         while (argc--) {
738                 int anydirskipped2;
739                 char *p = *argv;
740                 /* check if file is available */
741                 if (STAT(p, &statbuf) == -1) {
742                         msg("File cannot be accessed (%s).\n", p);
743                         msg("The ENTIRE dump is aborted.\n");
744                         exit(X_STARTUP);
745                 }
746                 /* check if file is on same unix partiton as the first 
747                  * argument */
748                 if (statbuf.st_dev != filedev) {
749                         msg("Files are not on same file system (%s).\n", p);
750                         msg("The ENTIRE dump is aborted.\n");
751                         exit(X_STARTUP);
752                 }
753                 /* check if file is a directory */
754                 if (!(statbuf.st_mode & S_IFDIR))
755                         anydirskipped2 = maponefile(maxino, &tapesize, 
756                                                     p+strlen(dt->fs_file));
757                 else
758                         /* read directory inodes.
759                          * NOTE: nested directories are not recognized 
760                          * so inodes may be umped twice!
761                          */
762                         anydirskipped2 = mapfilesfromdir(maxino, &tapesize, 
763                                                          p+strlen(dt->fs_file));
764                 if (!anydirskipped)
765                         anydirskipped = anydirskipped2;
766                 argv++;
767         }               
768 #else
769         anydirskipped = mapfiles(maxino, &tapesize);
770 #endif
771
772         if (!sizest)
773                 msg("mapping (Pass II) [directories]\n");
774         while (anydirskipped) {
775                 anydirskipped = mapdirs(maxino, &tapesize);
776         }
777
778         if (sizest) {
779                 printf("%.0f\n", ((double)tapesize + 1 + ntrec) * TP_BSIZE);
780                 exit(X_FINOK);
781         } /* stop here for size estimate */
782
783         if (pipeout || unlimited) {
784                 tapesize += 1 + ntrec;  /* 1 map header + trailer blocks */
785                 msg("estimated %ld tape blocks.\n", tapesize);
786         } else {
787                 double fetapes;
788
789                 if (blocksperfile)
790                         fetapes = (double) tapesize / blocksperfile;
791                 else if (cartridge) {
792                         /* Estimate number of tapes, assuming streaming stops at
793                            the end of each block written, and not in mid-block.
794                            Assume no erroneous blocks; this can be compensated
795                            for with an artificially low tape size. */
796                         fetapes =
797                         (         (double) tapesize     /* blocks */
798                                 * TP_BSIZE      /* bytes/block */
799                                 * (1.0/density) /* 0.1" / byte " */
800                           +
801                                   (double) tapesize     /* blocks */
802                                 * (1.0/ntrec)   /* streaming-stops per block */
803                                 * 15.48         /* 0.1" / streaming-stop " */
804                         ) * (1.0 / tsize );     /* tape / 0.1" " */
805                 } else {
806                         /* Estimate number of tapes, for old fashioned 9-track
807                            tape */
808                         int tenthsperirg = (density == 625) ? 3 : 7;
809                         fetapes =
810                         (         (double) tapesize     /* blocks */
811                                 * TP_BSIZE      /* bytes / block */
812                                 * (1.0/density) /* 0.1" / byte " */
813                           +
814                                   (double) tapesize     /* blocks */
815                                 * (1.0/ntrec)   /* IRG's / block */
816                                 * tenthsperirg  /* 0.1" / IRG " */
817                         ) * (1.0 / tsize );     /* tape / 0.1" " */
818                 }
819                 etapes = fetapes;               /* truncating assignment */
820                 etapes++;
821                 /* count the dumped inodes map on each additional tape */
822                 tapesize += (etapes - 1) *
823                         (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
824                 tapesize += etapes + ntrec;     /* headers + trailer blks */
825                 msg("estimated %ld tape blocks on %3.2f tape(s).\n",
826                     tapesize, fetapes);
827         }
828
829 #ifdef USE_QFA
830         if (tapepos) {
831                 msg("writing QFA positions to %s\n", gTapeposfile);
832                 if ((gTapeposfd = open(gTapeposfile, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR)) < 0)
833                         quit("can't open tapeposfile\n");
834                 /* print QFA-file header */
835                 sprintf(gTps, "%s\n%s\n%ld\n\n", QFA_MAGIC, QFA_VERSION, (unsigned long)spcl.c_date);
836                 if (write(gTapeposfd, gTps, strlen(gTps)) != strlen(gTps))
837                         quit("can't write tapeposfile\n");
838                 sprintf(gTps, "ino\ttapeno\ttapepos\n");
839                 if (write(gTapeposfd, gTps, strlen(gTps)) != strlen(gTps))
840                         quit("can't write tapeposfile\n");
841         }
842 #endif /* USE_QFA */
843
844         /*
845          * Allocate tape buffer.
846          */
847         if (!alloctape())
848                 quit(
849         "can't allocate tape buffers - try a smaller blocking factor.\n");
850
851         startnewtape(1);
852         tstart_writing = time(NULL);
853         dumpmap(usedinomap, TS_CLRI, maxino - 1);
854
855         msg("dumping (Pass III) [directories]\n");
856         dirty = 0;              /* XXX just to get gcc to shut up */
857         for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
858                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
859                         dirty = *map++;
860                 else
861                         dirty >>= 1;
862                 if ((dirty & 1) == 0)
863                         continue;
864                 /*
865                  * Skip directory inodes deleted and maybe reallocated
866                  */
867                 dp = getino(ino);
868                 if ((dp->di_mode & IFMT) != IFDIR)
869                         continue;
870 #ifdef  __linux__
871                 /*
872                  * Skip directory inodes deleted and not yes reallocated...
873                  */
874                 if (dp->di_nlink == 0 || dp->di_dtime != 0)
875                         continue;
876                 (void)dumpdirino(dp, ino);
877 #else
878                 (void)dumpino(dp, ino);
879 #endif
880         }
881
882         msg("dumping (Pass IV) [regular files]\n");
883         for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
884                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
885                         dirty = *map++;
886                 else
887                         dirty >>= 1;
888                 if ((dirty & 1) == 0)
889                         continue;
890                 /*
891                  * Skip inodes deleted and reallocated as directories.
892                  */
893                 dp = getino(ino);
894                 if ((dp->di_mode & IFMT) == IFDIR)
895                         continue;
896 #ifdef __linux__
897                 /*
898                  * No need to check here for deleted and not yet reallocated
899                  * inodes since this is done in dumpino().
900                  */
901 #endif
902                 (void)dumpino(dp, ino);
903         }
904
905         tend_writing = time(NULL);
906         spcl.c_type = TS_END;
907         /*
908          * Finish off the current tape record with trailer blocks, to ensure
909          * at least the data in the last partial record makes it to tape.
910          * Also make sure we write at least 1 trailer block.
911          */
912         for (i = ntrec - (spcl.c_tapea % ntrec); i; --i)
913                 writeheader(maxino - 1);
914
915         tnow = trewind();
916
917         if (pipeout || fifoout)
918                 msg("%ld tape blocks (%.2fMB)\n", spcl.c_tapea,
919                         ((double)spcl.c_tapea * TP_BSIZE / 1048576));
920         else
921                 msg("%ld tape blocks (%.2fMB) on %d volume(s)\n",
922                     spcl.c_tapea, 
923                     ((double)spcl.c_tapea * TP_BSIZE / 1048576),
924                     spcl.c_volume);
925
926         /* report dump performance, avoid division by zero */
927         if (tend_writing - tstart_writing == 0)
928                 msg("finished in less than a second\n");
929         else
930                 msg("finished in %d seconds, throughput %d kBytes/sec\n",
931                     tend_writing - tstart_writing,
932                     spcl.c_tapea / (tend_writing - tstart_writing));
933
934         putdumptime();
935         msg("Date of this level %c dump: %s", level,
936                 spcl.c_date == 0 ? "the epoch\n" : ctime4(&spcl.c_date));
937         msg("Date this dump completed:  %s", ctime(&tnow));
938
939         msg("Average transfer rate: %ld kB/s\n", xferrate / tapeno);
940         if (compressed) {
941                 long tapekb = bytes_written / 1024;
942                 double rate = .0005 + (double) spcl.c_tapea / tapekb;
943                 msg("Wrote %ldkB uncompressed, %ldkB compressed, %1.3f:1\n",
944                         spcl.c_tapea, tapekb, rate);
945         }
946
947         broadcast("DUMP IS DONE!\7\7\n");
948         msg("DUMP IS DONE\n");
949         Exit(X_FINOK);
950         /* NOTREACHED */
951         return 0;       /* gcc - shut up */
952 }
953
954 static void
955 usage(void)
956 {
957         char white[MAXPATHLEN];
958         const char *ext2ver, *ext2date;
959
960         memset(white, ' ', MAXPATHLEN);
961         white[MIN(strlen(__progname), MAXPATHLEN - 1)] = '\0';
962
963 #ifdef __linux__
964         ext2fs_get_library_version(&ext2ver, &ext2date);
965         fprintf(stderr, "%s %s (using libext2fs %s of %s)\n",
966                 __progname, _DUMP_VERSION, ext2ver, ext2date);
967 #else
968         fprintf(stderr, "%s %s\n", __progname, _DUMP_VERSION);
969 #endif
970         fprintf(stderr,
971                 "usage:\t%s [-0123456789ac"
972 #ifdef KERBEROS
973                 "k"
974 #endif
975                 "MnqSu"
976                 "] [-B records] [-b blocksize] [-d density]\n"
977                 "\t%s [-e inode#,inode#,...] [-E file] [-f file] [-h level] "
978 #ifdef HAVE_BZLIB
979                 "[-j zlevel] "
980 #endif
981                 "\n\t%s "
982 #ifdef USE_QFA
983                 "[-Q file] "
984 #endif
985                 "[-s feet] [-T date] "
986 #ifdef HAVE_ZLIB
987                 "[-z zlevel] "
988 #endif
989                 "filesystem\n"
990                 "\t%s [-W | -w]\n", 
991                 __progname, white, white, __progname);
992         exit(X_STARTUP);
993 }
994
995 /*
996  * Pick up a numeric argument.  It must be nonnegative and in the given
997  * range (except that a vmax of 0 means unlimited).
998  */
999 static long
1000 numarg(const char *meaning, long vmin, long vmax)
1001 {
1002         char *p;
1003         long val;
1004
1005         val = strtol(optarg, &p, 10);
1006         if (*p)
1007                 errx(X_STARTUP, "illegal %s -- %s", meaning, optarg);
1008         if (val < vmin || (vmax && val > vmax))
1009                 errx(X_STARTUP, "%s must be between %ld and %ld", meaning, vmin, vmax);
1010         return (val);
1011 }
1012
1013 void
1014 sig(int signo)
1015 {
1016         switch(signo) {
1017         case SIGALRM:
1018         case SIGBUS:
1019         case SIGFPE:
1020         case SIGHUP:
1021         case SIGTERM:
1022         case SIGTRAP:
1023                 if (pipeout || fifoout)
1024                         quit("Signal on pipe: cannot recover\n");
1025                 msg("Rewriting attempted as response to unknown signal: %d.\n", signo);
1026                 (void)fflush(stderr);
1027                 (void)fflush(stdout);
1028                 close_rewind();
1029                 exit(X_REWRITE);
1030                 /* NOTREACHED */
1031         case SIGSEGV:
1032                 msg("SIGSEGV: ABORTING!\n");
1033                 (void)signal(SIGSEGV, SIG_DFL);
1034                 (void)kill(0, SIGSEGV);
1035                 /* NOTREACHED */
1036         }
1037 }
1038
1039 const char *
1040 rawname(const char *cp)
1041 {
1042 #ifdef  __linux__
1043         return cp;
1044 #else   /* __linux__ */
1045         static char rawbuf[MAXPATHLEN];
1046         char *dp = strrchr(cp, '/');
1047
1048         if (dp == NULL)
1049                 return (NULL);
1050         (void)strncpy(rawbuf, cp, min(dp-cp, MAXPATHLEN - 1));
1051         rawbuf[min(dp-cp, MAXPATHLEN-1)] = '\0';
1052         (void)strncat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
1053         (void)strncat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
1054         return (rawbuf);
1055 #endif  /* __linux__ */
1056 }
1057
1058 /*
1059  * obsolete --
1060  *      Change set of key letters and ordered arguments into something
1061  *      getopt(3) will like.
1062  */
1063 static void
1064 obsolete(int *argcp, char **argvp[])
1065 {
1066         int argc, flags;
1067         char *ap, **argv, *flagsp=NULL, **nargv, *p=NULL;
1068
1069         /* Setup. */
1070         argv = *argvp;
1071         argc = *argcp;
1072
1073         /* Return if no arguments or first argument has leading dash. */
1074         ap = argv[1];
1075         if (argc == 1 || *ap == '-')
1076                 return;
1077
1078         /* Allocate space for new arguments. */
1079         if ((*argvp = nargv = malloc((argc + 1) * sizeof(char *))) == NULL ||
1080             (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
1081                 err(X_STARTUP, "malloc new args");
1082
1083         *nargv++ = *argv;
1084         argv += 2;
1085
1086         for (flags = 0; *ap; ++ap) {
1087                 switch (*ap) {
1088                 case 'B':
1089                 case 'b':
1090                 case 'd':
1091                 case 'e':
1092                 case 'E':
1093                 case 'f':
1094                 case 'F':
1095                 case 'h':
1096                 case 'L':
1097                 case 'Q':
1098                 case 's':
1099                 case 'T':
1100                         if (*argv == NULL) {
1101                                 warnx("option requires an argument -- %c", *ap);
1102                                 usage();
1103                         }
1104                         if ((nargv[0] = malloc(strlen(*argv) + 2 + 1)) == NULL)
1105                                 err(X_STARTUP, "malloc arg");
1106                         nargv[0][0] = '-';
1107                         nargv[0][1] = *ap;
1108                         (void)strcpy(&nargv[0][2], *argv);
1109                         ++argv;
1110                         ++nargv;
1111                         break;
1112                 default:
1113                         if (!flags) {
1114                                 *p++ = '-';
1115                                 flags = 1;
1116                         }
1117                         *p++ = *ap;
1118                         break;
1119                 }
1120         }
1121
1122         /* Terminate flags. */
1123         if (flags) {
1124                 *p = '\0';
1125                 *nargv++ = flagsp;
1126         }
1127
1128         /* Copy remaining arguments. */
1129         while ((*nargv++ = *argv++));
1130
1131         /* Update argument count. */
1132         *argcp = nargv - *argvp - 1;
1133 }
1134
1135 /*
1136  * This tests whether an inode is in the exclude list
1137  */
1138 int
1139 exclude_ino(dump_ino_t ino)
1140 {
1141         /* 04-Feb-00 ILC */
1142         if (iexclude_num) {     /* if there are inodes in the exclude list */
1143                 int idx;        /* then check this inode against it */
1144                 for (idx = 0; idx < iexclude_num; idx++)
1145                         if (ino == iexclude_list[idx])
1146                                 return 1;
1147         }
1148         return 0;
1149 }
1150
1151 /*
1152  * This tests adds an inode to the exclusion list if it isn't already there
1153  */
1154 void
1155 do_exclude_ino(dump_ino_t ino, const char *reason)
1156 {
1157         if (!exclude_ino(ino)) {
1158                 if (iexclude_num == IEXCLUDE_MAXNUM) {
1159                         msg("Too many exclude options\n");
1160                         msg("The ENTIRE dump is aborted.\n");
1161                         exit(X_STARTUP);
1162                 }
1163                 if (reason)
1164                         msg("Added inode %u to exclude list (%s)\n", 
1165                             ino, reason);
1166                 else
1167                         msg("Added inode %u to exclude list\n", ino);
1168                 iexclude_list[iexclude_num++] = ino;
1169         }
1170 }
1171
1172 static void
1173 do_exclude_ino_str(char * ino) {
1174         char *r;
1175         unsigned long inod;
1176
1177         inod = strtoul(ino, &r, 10);
1178         if (*r != '\0' || inod <= ROOTINO) {
1179                 msg("Invalid inode argument %s\n", ino);
1180                 msg("The ENTIRE dump is aborted.\n");
1181                 exit(X_STARTUP);
1182         }
1183         do_exclude_ino(inod, NULL);
1184 }
1185
1186 /*
1187  * This reads a file containing one inode number per line and exclude them all
1188  */
1189 static void 
1190 do_exclude_from_file(char *file) {
1191         FILE *f;
1192         char *p, fname[MAXPATHLEN];
1193         
1194
1195         if (!( f = fopen(file, "r")) ) {
1196                 msg("Cannot open file for reading: %s\n", file);
1197                 msg("The ENTIRE dump is aborted.\n");
1198                 exit(X_STARTUP);
1199         }
1200         while (( p = fgets(fname, MAXPATHLEN, f))) {
1201                 if ( *p && *(p + strlen(p) - 1) == '\n' ) /* possible null string */
1202                         *(p + strlen(p) - 1) = '\0';
1203                 if ( !*p ) /* skip empty lines */
1204                         continue;
1205                 do_exclude_ino_str(p);
1206         }
1207         fclose(f);
1208 }
1209
1210 static void incompat_flags(int cond, char flag1, char flag2) {
1211         if (cond) {
1212                 msg("You cannot use the %c and %c flags together.\n", 
1213                     flag1, flag2);
1214                 msg("The ENTIRE dump is aborted.\n");
1215                 exit(X_STARTUP);
1216         }
1217 }