]> git.wh0rd.org Git - dump.git/blob - dump/main.c
-B option knows about compression length now.
[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.51 2001/07/18 09:50:48 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 int     notify = 0;     /* notify operator flag */
92 int     blockswritten = 0;      /* number of blocks written on current tape */
93 int     tapeno = 0;     /* current tape number */
94 int     density = 0;    /* density in bytes/0.1" " <- this is for hilit19 */
95 int     ntrec = NTREC;  /* # tape blocks in each tape record */
96 int     cartridge = 0;  /* Assume non-cartridge tape */
97 #ifdef USE_QFA
98 int     tapepos = 0;    /* assume no QFA tapeposition needed by user */
99 #endif /* USE_QFA */
100 int     dokerberos = 0; /* Use Kerberos authentication */
101 long    dev_bsize = 1;  /* recalculated below */
102 long    blocksperfile;  /* output blocks per file */
103 char    *host = NULL;   /* remote host (if any) */
104 int     sizest = 0;     /* return size estimate only */
105 int     compressed = 0; /* use zlib to compress the output, compress level 1-9 */
106 long long bytes_written = 0; /* total bytes written */
107 long    uncomprblks = 0;/* uncompressed blocks written */
108
109 #ifdef  __linux__
110 char    *__progname;
111 #endif
112
113 int     maxbsize = 64*1024;     /* XXX MAXBSIZE from sys/param.h */
114 static long numarg __P((const char *, long, long));
115 static void obsolete __P((int *, char **[]));
116 static void usage __P((void));
117
118 dump_ino_t iexclude_list[IEXCLUDE_MAXNUM];/* the inode exclude list */
119 int iexclude_num = 0;                   /* number of elements in the list */
120
121 int
122 main(int argc, char *argv[])
123 {
124         register dump_ino_t ino;
125         register int dirty;
126         register struct dinode *dp;
127         register struct fstab *dt;
128         register char *map;
129         register int ch;
130         int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
131         dump_ino_t maxino;
132         struct STAT statbuf;
133         dev_t filedev = 0;
134 #ifdef  __linux__
135         errcode_t retval;
136         char directory[MAXPATHLEN];
137         char pathname[MAXPATHLEN];
138 #endif
139         time_t tnow;
140         char *diskparam;
141
142         spcl.c_label[0] = '\0';
143         spcl.c_date = time(NULL);
144
145 #ifdef __linux__
146         __progname = argv[0];
147         directory[0] = 0;
148         initialize_ext2_error_table();
149 #endif
150
151         tsize = 0;      /* Default later, based on 'c' option for cart tapes */
152         unlimited = 1;
153         eot_script = NULL;
154         if ((tapeprefix = getenv("TAPE")) == NULL)
155                 tapeprefix = _PATH_DEFTAPE;
156         dumpdates = _PATH_DUMPDATES;
157         if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
158                 quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
159         level = '0';
160
161         if (argc < 2)
162                 usage();
163
164         obsolete(&argc, &argv);
165
166 #ifdef USE_QFA
167         gTapeposfd = -1;
168 #endif /* USE_QFA */
169
170         while ((ch = getopt(argc, argv,
171                             "0123456789aB:b:cd:e:f:F:h:L:"
172 #ifdef KERBEROS
173                             "k"
174 #endif
175                             "Mn"
176 #ifdef USE_QFA
177                             "Q:"
178 #endif
179                             "s:ST:uWw"
180 #ifdef HAVE_ZLIB
181                             "z::"
182 #endif
183                             )) != -1)
184                 switch (ch) {
185                 /* dump level */
186                 case '0': case '1': case '2': case '3': case '4':
187                 case '5': case '6': case '7': case '8': case '9':
188                         level = ch;
189                         break;
190
191                 case 'a':               /* `auto-size', Write to EOM. */
192                         unlimited = 1;
193                         break;
194
195                 case 'B':               /* blocks per output file */
196                         unlimited = 0;
197                         blocksperfile = numarg("number of blocks per file",
198                             1L, 0L);
199                         break;
200
201                 case 'b':               /* blocks per tape write */
202                         ntrec = numarg("number of blocks per write",
203                             1L, 1000L);
204                         if (ntrec > maxbsize/1024) {
205                                 msg("Please choose a blocksize <= %dkB\n",
206                                         maxbsize/1024);
207                                 msg("The ENTIRE dump is aborted.\n");
208                                 exit(X_STARTUP);
209                         }
210                         bflag = 1;
211                         break;
212
213                 case 'c':               /* Tape is cart. not 9-track */
214                         unlimited = 0;
215                         cartridge = 1;
216                         break;
217
218                 case 'd':               /* density, in bits per inch */
219                         unlimited = 0;
220                         density = numarg("density", 10L, 327670L) / 10;
221                         if (density >= 625 && !bflag)
222                                 ntrec = HIGHDENSITYTREC;
223                         break;
224                         
225                                         /* 04-Feb-00 ILC */
226                 case 'e':               /* exclude an inode */
227                         if (iexclude_num == IEXCLUDE_MAXNUM) {
228                                 msg("Too many -e options\n");
229                                 msg("The ENTIRE dump is aborted.\n");
230                                 exit(X_STARTUP);
231                         }
232                         iexclude_list[iexclude_num++] = numarg("inode to exclude",0L,0L);
233                         if (iexclude_list[iexclude_num-1] <= ROOTINO) {
234                                 msg("Cannot exclude inode %ld\n", (long)iexclude_list[iexclude_num-1]);
235                                 msg("The ENTIRE dump is aborted.\n");
236                                 exit(X_STARTUP);
237                         }
238                         msg("Added %d to exclude list\n",
239                             iexclude_list[iexclude_num-1]);
240                         break;
241
242                 case 'f':               /* output file */
243                         tapeprefix = optarg;
244                         break;
245
246                 case 'F':               /* end of tape script */
247                         eot_script = optarg;
248                         break;
249
250                 case 'h':
251                         honorlevel = numarg("honor level", 0L, 10L);
252                         break;
253
254 #ifdef KERBEROS
255                 case 'k':
256                         dokerberos = 1;
257                         break;
258 #endif
259
260                 case 'L':
261                         /*
262                          * Note that although there are LBLSIZE characters,
263                          * the last must be '\0', so the limit on strlen()
264                          * is really LBLSIZE-1.
265                          */
266                         strncpy(spcl.c_label, optarg, LBLSIZE);
267                         spcl.c_label[LBLSIZE-1] = '\0';
268                         if (strlen(optarg) > LBLSIZE-1) {
269                                 msg(
270                 "WARNING Label `%s' is larger than limit of %d characters.\n",
271                                     optarg, LBLSIZE-1);
272                                 msg("WARNING: Using truncated label `%s'.\n",
273                                     spcl.c_label);
274                         }
275                         break;
276
277                 case 'M':               /* multi-volume flag */
278                         Mflag = 1;
279                         break;
280
281                 case 'n':               /* notify operators */
282                         notify = 1;
283                         break;
284
285 #ifdef USE_QFA
286                 case 'Q':               /* create tapeposfile */
287                         gTapeposfile = optarg;
288                         tapepos = 1;
289                         break;
290 #endif /* USE_QFA */
291                         
292                 case 's':               /* tape size, feet */
293                         unlimited = 0;
294                         tsize = numarg("tape size", 1L, 0L) * 12 * 10;
295                         break;
296
297                 case 'S':
298                         sizest = 1;     /* return size estimate only */
299                         break;
300
301                 case 'T':               /* time of last dump */
302                         spcl.c_ddate = unctime(optarg);
303                         if (spcl.c_ddate < 0) {
304                                 msg("bad time \"%s\"\n", optarg);
305                                 msg("The ENTIRE dump is aborted.\n");
306                                 exit(X_STARTUP);
307                         }
308                         Tflag = 1;
309                         lastlevel = '?';
310                         break;
311
312                 case 'u':               /* update dumpdates */
313                         uflag = 1;
314                         break;
315
316                 case 'W':               /* what to do */
317                 case 'w':
318                         lastdump(ch);
319                         exit(X_FINOK);  /* do nothing else */
320 #ifdef HAVE_ZLIB
321                 case 'z':
322                         compressed = 2;
323                         if (optarg)
324                                 compressed = numarg("compress level", 1L, 9L);
325                         break;
326 #endif /* HAVE_ZLIB */
327
328                 default:
329                         usage();
330                 }
331         argc -= optind;
332         argv += optind;
333
334         if (argc < 1) {
335                 msg("Must specify disk or filesystem\n");
336                 msg("The ENTIRE dump is aborted.\n");
337                 exit(X_STARTUP);
338         }
339         diskparam = *argv++;
340         if (strlen(diskparam) >= MAXPATHLEN) {
341                 msg("Disk or filesystem name too long: %s\n", diskparam);
342                 msg("The ENTIRE dump is aborted.\n");
343                 exit(X_STARTUP);
344         }
345         argc--;
346         if (Tflag && uflag) {
347                 msg("You cannot use the T and u flags together.\n");
348                 msg("The ENTIRE dump is aborted.\n");
349                 exit(X_STARTUP);
350         }
351         if (strcmp(tapeprefix, "-") == 0) {
352                 pipeout++;
353                 tapeprefix = "standard output";
354         }
355
356         if (blocksperfile && !compressed)
357                 blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
358         else if (!unlimited) {
359                 /*
360                  * Determine how to default tape size and density
361                  *
362                  *              density                         tape size
363                  * 9-track      1600 bpi (160 bytes/.1")        2300 ft.
364                  * 9-track      6250 bpi (625 bytes/.1")        2300 ft.
365                  * cartridge    8000 bpi (100 bytes/.1")        1700 ft.
366                  *                                              (450*4 - slop)
367                  * hilit19 hits again: "
368                  */
369                 if (density == 0)
370                         density = cartridge ? 100 : 160;
371                 if (tsize == 0)
372                         tsize = cartridge ? 1700L*120L : 2300L*120L;
373         }
374
375         if (strchr(tapeprefix, ':')) {
376                 host = tapeprefix;
377                 tapeprefix = strchr(host, ':');
378                 *tapeprefix++ = '\0';
379 #ifdef RDUMP
380                 if (index(tapeprefix, '\n')) {
381                         msg("invalid characters in tape\n");
382                         msg("The ENTIRE dump is aborted.\n");
383                         exit(X_STARTUP);
384                 }
385                 if (rmthost(host) == 0)
386                         exit(X_STARTUP);
387 #else
388                 msg("remote dump not enabled\n");
389                 msg("The ENTIRE dump is aborted.\n");
390                 exit(X_STARTUP);
391 #endif
392         }
393         (void)setuid(getuid()); /* rmthost() is the only reason to be setuid */
394
395         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
396                 signal(SIGHUP, sig);
397         if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
398                 signal(SIGTRAP, sig);
399         if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
400                 signal(SIGFPE, sig);
401         if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
402                 signal(SIGBUS, sig);
403         if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
404                 signal(SIGSEGV, sig);
405         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
406                 signal(SIGTERM, sig);
407         if (signal(SIGINT, interrupt) == SIG_IGN)
408                 signal(SIGINT, SIG_IGN);
409         set_operators();        /* /etc/group snarfed */
410         getfstab();             /* /etc/fstab snarfed */
411
412         /*
413          *      disk may end in / and this can confuse
414          *      fstabsearch.
415          */
416         i = strlen(diskparam) - 1;
417         if (i > 1 && diskparam[i] == '/')
418                 diskparam[i] = '\0';
419
420         disk = get_device_name(diskparam);
421         if (!disk) {            /* null means the disk is some form
422                                    of LABEL= or UID= but it was not
423                                    found */
424                 msg("Cannot find a disk having %s\n", diskparam);
425                 msg("The ENTIRE dump is aborted.\n");
426                 exit(X_STARTUP);
427         }
428         /*
429          *      disk can be either the full special file name,
430          *      the suffix of the special file name,
431          *      the special name missing the leading '/',
432          *      the file system name with or without the leading '/'.
433          */
434         if ((dt = fstabsearch(disk)) != NULL) {
435                 /* if found then only one parameter (i.e. partition)
436                  * is allowed */
437                 if (argc >= 1) {
438                         (void)fprintf(stderr, "Unknown arguments to dump:");
439                         while (argc--)
440                                 (void)fprintf(stderr, " %s", *argv++);
441                         (void)fprintf(stderr, "\n");
442                         msg("The ENTIRE dump is aborted.\n");
443                         exit(X_STARTUP);
444                 }
445                 disk = rawname(dt->fs_spec);
446                 (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
447                 (void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
448         } else {
449 #ifdef  __linux__
450 #ifdef  HAVE_REALPATH
451                 if (realpath(disk, pathname) == NULL)
452 #endif
453                         strcpy(pathname, disk);
454                 /*
455                  * The argument could be now a mountpoint of
456                  * a filesystem specified in fstab. Search for it.
457                  */
458                 if ((dt = fstabsearch(pathname)) != NULL) {
459                         disk = rawname(dt->fs_spec);
460                         (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
461                         (void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
462                 } else {
463                         /*
464                          * The argument was not found in the fstab
465                          * assume that this is a subtree and search for it
466                          */
467                         dt = fstabsearchdir(pathname, directory);
468                         if (dt != NULL) {
469                                 char name[MAXPATHLEN];
470                                 (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
471                                 (void)snprintf(name, sizeof(name), "%s (dir %s)",
472                                               dt->fs_file, directory);
473                                 (void)strncpy(spcl.c_filesys, name, NAMELEN);
474                                 disk = rawname(dt->fs_spec);
475                         } else {
476                                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
477                                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
478                                     NAMELEN);
479                         }
480                 }
481 #else
482                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
483                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
484                     NAMELEN);
485 #endif
486         }
487
488         if (directory[0] != 0) {
489                 if (level != '0') {
490                         msg("Only level 0 dumps are allowed on a subdirectory\n");
491                         msg("The ENTIRE dump is aborted.\n");
492                         exit(X_STARTUP);
493                 }
494                 if (uflag) {
495                         msg("You can't update the dumpdates file when dumping a subdirectory\n");
496                         msg("The ENTIRE dump is aborted.\n");
497                         exit(X_STARTUP);
498                 }
499         }
500         spcl.c_dev[NAMELEN-1] = '\0';
501         spcl.c_filesys[NAMELEN-1] = '\0';
502         (void)gethostname(spcl.c_host, NAMELEN);
503         spcl.c_host[NAMELEN-1] = '\0';
504         spcl.c_level = level - '0';
505         spcl.c_type = TS_TAPE;
506         if (!Tflag)
507                 getdumptime(uflag);             /* dumpdates snarfed */
508
509         if (spcl.c_ddate == 0 && spcl.c_level) {
510                 msg("WARNING: There is no inferior level dump on this filesystem\n"); 
511                 msg("WARNING: Assuming a level 0 dump by default\n");
512                 level = '0';
513                 spcl.c_level = 0;
514         }
515
516         if (Mflag)
517                 snprintf(tape, MAXPATHLEN, "%s%03d", tapeprefix, tapeno + 1);
518         else
519                 strncpy(tape, tapeprefix, MAXPATHLEN);
520         tape[MAXPATHLEN - 1] = '\0';
521
522         if (!pipeout) {
523                 if (STAT(tape, &statbuf) != -1)
524                         fifoout= statbuf.st_mode & S_IFIFO;
525         }
526
527         if (!sizest) {
528
529                 msg("Date of this level %c dump: %s", level,
530                     ctime4(&spcl.c_date));
531                 if (spcl.c_ddate)
532                         msg("Date of last level %c dump: %s", lastlevel,
533                             ctime4(&spcl.c_ddate));
534                 msg("Dumping %s (%s) ", disk, spcl.c_filesys);
535                 if (host)
536                         msgtail("to %s on host %s\n", tape, host);
537                 else
538                         msgtail("to %s\n", tape);
539         } /* end of size estimate */
540
541 #ifdef  __linux__
542         retval = dump_fs_open(disk, &fs);
543         if (retval) {
544                 com_err(disk, retval, "while opening filesystem");
545                 if (retval == EXT2_ET_REV_TOO_HIGH)
546                         msg("Get a newer version of dump!\n");
547                 msg("The ENTIRE dump is aborted.\n");
548                 exit(X_STARTUP);
549         }
550         if (fs->super->s_rev_level > DUMP_CURRENT_REV) {
551                 com_err(disk, retval, "while opening filesystem");
552                 msg("Get a newer version of dump!\n");
553                 msg("The ENTIRE dump is aborted.\n");
554                 exit(X_STARTUP);
555         }
556         if ((diskfd = OPEN(disk, O_RDONLY)) < 0) {
557                 msg("Cannot open %s\n", disk);
558                 msg("The ENTIRE dump is aborted.\n");
559                 exit(X_STARTUP);
560         }
561         /* if no user label specified, use ext2 filesystem label if available */
562         if (spcl.c_label[0] == '\0') {
563                 const char *lbl;
564                 if ( (lbl = get_device_label(disk)) != NULL) {
565                         strncpy(spcl.c_label, lbl, LBLSIZE);
566                         spcl.c_label[LBLSIZE-1] = '\0';
567                 }
568                 else
569                         strcpy(spcl.c_label, "none");   /* safe strcpy. */
570         }
571         sync();
572         dev_bsize = DEV_BSIZE;
573         dev_bshift = ffs(dev_bsize) - 1;
574         if (dev_bsize != (1 << dev_bshift))
575                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
576         tp_bshift = ffs(TP_BSIZE) - 1;
577         if (TP_BSIZE != (1 << tp_bshift))
578                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
579         maxino = fs->super->s_inodes_count;
580 #if     0
581         spcl.c_flags |= DR_NEWINODEFMT;
582 #endif
583 #else   /* __linux __*/
584         if ((diskfd = open(disk, O_RDONLY)) < 0) {
585                 msg("Cannot open %s\n", disk);
586                 msg("The ENTIRE dump is aborted.\n");
587                 exit(X_STARTUP);
588         }
589         sync();
590         sblock = (struct fs *)sblock_buf;
591         bread(SBOFF, (char *) sblock, SBSIZE);
592         if (sblock->fs_magic != FS_MAGIC)
593                 quit("bad sblock magic number\n");
594         dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
595         dev_bshift = ffs(dev_bsize) - 1;
596         if (dev_bsize != (1 << dev_bshift))
597                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
598         tp_bshift = ffs(TP_BSIZE) - 1;
599         if (TP_BSIZE != (1 << tp_bshift))
600                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
601 #ifdef FS_44INODEFMT
602         if (sblock->fs_inodefmt >= FS_44INODEFMT)
603                 spcl.c_flags |= DR_NEWINODEFMT;
604 #endif
605         maxino = sblock->fs_ipg * sblock->fs_ncg;
606 #endif  /* __linux__ */
607         mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
608         usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
609         dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
610         dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
611         if (usedinomap == NULL || dumpdirmap == NULL || dumpinomap == NULL)
612                 quit("out of memory allocating inode maps\n");
613         tapesize = 2 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
614
615         nonodump = spcl.c_level < honorlevel;
616
617         if (!sizest) {
618                 msg("Label: %s\n", spcl.c_label);
619
620                 if (compressed)
621                         msg("Compressing output at compression level %d\n", 
622                             compressed);
623         }
624
625 #if defined(SIGINFO)
626         (void)signal(SIGINFO, statussig);
627 #endif
628
629         if (!sizest)
630                 msg("mapping (Pass I) [regular files]\n");
631 #ifdef  __linux__
632         if (directory[0] == 0)
633                 anydirskipped = mapfiles(maxino, &tapesize);
634         else {
635                 if (STAT(pathname, &statbuf) == -1) {
636                         msg("File cannot be accessed (%s).\n", pathname);
637                         msg("The ENTIRE dump is aborted.\n");
638                         exit(X_STARTUP);
639                 }
640                 filedev = statbuf.st_dev;
641                 if (!(statbuf.st_mode & S_IFDIR))       /* is a file */
642                         anydirskipped = maponefile(maxino, &tapesize, 
643                                                    directory);
644                 else
645                         anydirskipped = mapfilesfromdir(maxino, &tapesize, 
646                                                         directory);
647         }
648         while (argc--) {
649                 int anydirskipped2;
650                 char *p = *argv;
651                 /* check if file is available */
652                 if (STAT(p, &statbuf) == -1) {
653                         msg("File cannot be accessed (%s).\n", p);
654                         msg("The ENTIRE dump is aborted.\n");
655                         exit(X_STARTUP);
656                 }
657                 /* check if file is on same unix partiton as the first 
658                  * argument */
659                 if (statbuf.st_dev != filedev) {
660                         msg("Files are not on same file system (%s).\n", p);
661                         msg("The ENTIRE dump is aborted.\n");
662                         exit(X_STARTUP);
663                 }
664                 /* check if file is a directory */
665                 if (!(statbuf.st_mode & S_IFDIR))
666                         anydirskipped2 = maponefile(maxino, &tapesize, 
667                                                     p+strlen(dt->fs_file));
668                 else
669                         /* read directory inodes.
670                          * NOTE: nested directories are not recognized 
671                          * so inodes may be umped twice!
672                          */
673                         anydirskipped2 = mapfilesfromdir(maxino, &tapesize, 
674                                                          p+strlen(dt->fs_file));
675                 if (!anydirskipped)
676                         anydirskipped = anydirskipped2;
677                 argv++;
678         }               
679 #else
680         anydirskipped = mapfiles(maxino, &tapesize);
681 #endif
682
683         if (!sizest)
684                 msg("mapping (Pass II) [directories]\n");
685         while (anydirskipped) {
686                 anydirskipped = mapdirs(maxino, &tapesize);
687         }
688
689         if (sizest) {
690                 printf("%.0f\n", ((double)tapesize + 1 + ntrec) * TP_BSIZE);
691                 exit(X_FINOK);
692         } /* stop here for size estimate */
693
694         if (pipeout || unlimited) {
695                 tapesize += 1 + ntrec;  /* 1 map header + trailer blocks */
696                 msg("estimated %ld tape blocks.\n", tapesize);
697         } else {
698                 double fetapes;
699
700                 if (blocksperfile)
701                         fetapes = (double) tapesize / blocksperfile;
702                 else if (cartridge) {
703                         /* Estimate number of tapes, assuming streaming stops at
704                            the end of each block written, and not in mid-block.
705                            Assume no erroneous blocks; this can be compensated
706                            for with an artificially low tape size. */
707                         fetapes =
708                         (         (double) tapesize     /* blocks */
709                                 * TP_BSIZE      /* bytes/block */
710                                 * (1.0/density) /* 0.1" / byte " */
711                           +
712                                   (double) tapesize     /* blocks */
713                                 * (1.0/ntrec)   /* streaming-stops per block */
714                                 * 15.48         /* 0.1" / streaming-stop " */
715                         ) * (1.0 / tsize );     /* tape / 0.1" " */
716                 } else {
717                         /* Estimate number of tapes, for old fashioned 9-track
718                            tape */
719                         int tenthsperirg = (density == 625) ? 3 : 7;
720                         fetapes =
721                         (         (double) tapesize     /* blocks */
722                                 * TP_BSIZE      /* bytes / block */
723                                 * (1.0/density) /* 0.1" / byte " */
724                           +
725                                   (double) tapesize     /* blocks */
726                                 * (1.0/ntrec)   /* IRG's / block */
727                                 * tenthsperirg  /* 0.1" / IRG " */
728                         ) * (1.0 / tsize );     /* tape / 0.1" " */
729                 }
730                 etapes = fetapes;               /* truncating assignment */
731                 etapes++;
732                 /* count the dumped inodes map on each additional tape */
733                 tapesize += (etapes - 1) *
734                         (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
735                 tapesize += etapes + ntrec;     /* headers + trailer blks */
736                 msg("estimated %ld tape blocks on %3.2f tape(s).\n",
737                     tapesize, fetapes);
738         }
739
740 #ifdef USE_QFA
741         if (tapepos) {
742                 msg("writing QFA positions to %s\n", gTapeposfile);
743                 if ((gTapeposfd = open(gTapeposfile, O_RDWR|O_CREAT)) < 0)
744                         quit("can't open tapeposfile\n");
745                 /* print QFA-file header */
746                 sprintf(gTps, "%s\n%s\n%ld\n\n", QFA_MAGIC, QFA_VERSION, (unsigned long)spcl.c_date);
747                 if (write(gTapeposfd, gTps, strlen(gTps)) != strlen(gTps))
748                         quit("can't write tapeposfile\n");
749                 sprintf(gTps, "ino\ttapeno\ttapepos\n");
750                 if (write(gTapeposfd, gTps, strlen(gTps)) != strlen(gTps))
751                         quit("can't write tapeposfile\n");
752         }
753 #endif /* USE_QFA */
754
755         /*
756          * Allocate tape buffer.
757          */
758         if (!alloctape())
759                 quit(
760         "can't allocate tape buffers - try a smaller blocking factor.\n");
761
762         startnewtape(1);
763         tstart_writing = time(NULL);
764         dumpmap(usedinomap, TS_CLRI, maxino - 1);
765
766         msg("dumping (Pass III) [directories]\n");
767         dirty = 0;              /* XXX just to get gcc to shut up */
768         for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
769                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
770                         dirty = *map++;
771                 else
772                         dirty >>= 1;
773                 if ((dirty & 1) == 0)
774                         continue;
775                 /*
776                  * Skip directory inodes deleted and maybe reallocated
777                  */
778                 dp = getino(ino);
779                 if ((dp->di_mode & IFMT) != IFDIR)
780                         continue;
781 #ifdef  __linux__
782                 /*
783                  * Skip directory inodes deleted and not yes reallocated...
784                  */
785                 if (dp->di_nlink == 0 || dp->di_dtime != 0)
786                         continue;
787                 (void)dumpdirino(dp, ino);
788 #else
789                 (void)dumpino(dp, ino);
790 #endif
791         }
792
793         msg("dumping (Pass IV) [regular files]\n");
794         for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
795                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
796                         dirty = *map++;
797                 else
798                         dirty >>= 1;
799                 if ((dirty & 1) == 0)
800                         continue;
801                 /*
802                  * Skip inodes deleted and reallocated as directories.
803                  */
804                 dp = getino(ino);
805                 if ((dp->di_mode & IFMT) == IFDIR)
806                         continue;
807 #ifdef __linux__
808                 /*
809                  * No need to check here for deleted and not yet reallocated
810                  * inodes since this is done in dumpino().
811                  */
812 #endif
813                 (void)dumpino(dp, ino);
814         }
815
816         tend_writing = time(NULL);
817         spcl.c_type = TS_END;
818         /*
819          * Finish off the current tape record with trailer blocks, to ensure
820          * at least the data in the last partial record makes it to tape.
821          * Also make sure we write at least 1 trailer block.
822          */
823         for (i = ntrec - (spcl.c_tapea % ntrec); i; --i)
824                 writeheader(maxino - 1);
825
826         tnow = trewind();
827
828         if (pipeout || fifoout)
829                 msg("%ld tape blocks (%.2fMB)\n", spcl.c_tapea,
830                         ((double)spcl.c_tapea * TP_BSIZE / 1048576));
831         else
832                 msg("%ld tape blocks (%.2fMB) on %d volume(s)\n",
833                     spcl.c_tapea, 
834                     ((double)spcl.c_tapea * TP_BSIZE / 1048576),
835                     spcl.c_volume);
836
837         /* report dump performance, avoid division by zero */
838         if (tend_writing - tstart_writing == 0)
839                 msg("finished in less than a second\n");
840         else
841                 msg("finished in %d seconds, throughput %d kBytes/sec\n",
842                     tend_writing - tstart_writing,
843                     spcl.c_tapea / (tend_writing - tstart_writing));
844
845         putdumptime();
846         msg("Date of this level %c dump: %s", level,
847                 spcl.c_date == 0 ? "the epoch\n" : ctime4(&spcl.c_date));
848         msg("Date this dump completed:  %s", ctime(&tnow));
849
850         msg("Average transfer rate: %ld kB/s\n", xferrate / tapeno);
851         if (compressed) {
852                 long tapekb = bytes_written / 1024;
853                 double rate = .0005 + (double) spcl.c_tapea / tapekb;
854                 msg("Wrote %ldkB uncompressed, %ldkB compressed, %1.3f:1\n",
855                         spcl.c_tapea, tapekb, rate);
856         }
857
858         broadcast("DUMP IS DONE!\7\7\n");
859         msg("DUMP IS DONE\n");
860         Exit(X_FINOK);
861         /* NOTREACHED */
862         return 0;       /* gcc - shut up */
863 }
864
865 static void
866 usage(void)
867 {
868         char white[MAXPATHLEN];
869         const char *ext2ver, *ext2date;
870
871         memset(white, ' ', MAXPATHLEN);
872         white[MIN(strlen(__progname), MAXPATHLEN - 1)] = '\0';
873
874 #ifdef __linux__
875         ext2fs_get_library_version(&ext2ver, &ext2date);
876         fprintf(stderr, "%s %s (using libext2fs %s of %s)\n",
877                 __progname, _DUMP_VERSION, ext2ver, ext2date);
878 #else
879         fprintf(stderr, "%s %s\n", __progname, _DUMP_VERSION);
880 #endif
881         fprintf(stderr,
882                 "usage:\t%s [-0123456789ac"
883 #ifdef KERBEROS
884                 "k"
885 #endif
886                 "MnSu"
887                 "] [-B records] [-b blocksize] [-d density]\n"
888                 "\t%s [-e inode#] [-f file] [-h level] "
889 #ifdef USE_QFA
890                 "[-Q file] "
891 #endif
892                 "[-s feet]\n"
893                 "\t%s [-T date] "
894 #ifdef HAVE_ZLIB
895                 "[-z zlevel] "
896 #endif
897                 "filesystem\n"
898                 "\t%s [-W | -w]\n", 
899                 __progname, white, white, __progname);
900         exit(X_STARTUP);
901 }
902
903 /*
904  * Pick up a numeric argument.  It must be nonnegative and in the given
905  * range (except that a vmax of 0 means unlimited).
906  */
907 static long
908 numarg(const char *meaning, long vmin, long vmax)
909 {
910         char *p;
911         long val;
912
913         val = strtol(optarg, &p, 10);
914         if (*p)
915                 errx(X_STARTUP, "illegal %s -- %s", meaning, optarg);
916         if (val < vmin || (vmax && val > vmax))
917                 errx(X_STARTUP, "%s must be between %ld and %ld", meaning, vmin, vmax);
918         return (val);
919 }
920
921 void
922 sig(int signo)
923 {
924         switch(signo) {
925         case SIGALRM:
926         case SIGBUS:
927         case SIGFPE:
928         case SIGHUP:
929         case SIGTERM:
930         case SIGTRAP:
931                 if (pipeout || fifoout)
932                         quit("Signal on pipe: cannot recover\n");
933                 msg("Rewriting attempted as response to unknown signal: %d.\n", signo);
934                 (void)fflush(stderr);
935                 (void)fflush(stdout);
936                 close_rewind();
937                 exit(X_REWRITE);
938                 /* NOTREACHED */
939         case SIGSEGV:
940                 msg("SIGSEGV: ABORTING!\n");
941                 (void)signal(SIGSEGV, SIG_DFL);
942                 (void)kill(0, SIGSEGV);
943                 /* NOTREACHED */
944         }
945 }
946
947 const char *
948 rawname(const char *cp)
949 {
950 #ifdef  __linux__
951         return cp;
952 #else   /* __linux__ */
953         static char rawbuf[MAXPATHLEN];
954         char *dp = strrchr(cp, '/');
955
956         if (dp == NULL)
957                 return (NULL);
958         (void)strncpy(rawbuf, cp, min(dp-cp, MAXPATHLEN - 1));
959         rawbuf[min(dp-cp, MAXPATHLEN-1)] = '\0';
960         (void)strncat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
961         (void)strncat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
962         return (rawbuf);
963 #endif  /* __linux__ */
964 }
965
966 /*
967  * obsolete --
968  *      Change set of key letters and ordered arguments into something
969  *      getopt(3) will like.
970  */
971 static void
972 obsolete(int *argcp, char **argvp[])
973 {
974         int argc, flags;
975         char *ap, **argv, *flagsp=NULL, **nargv, *p=NULL;
976
977         /* Setup. */
978         argv = *argvp;
979         argc = *argcp;
980
981         /* Return if no arguments or first argument has leading dash. */
982         ap = argv[1];
983         if (argc == 1 || *ap == '-')
984                 return;
985
986         /* Allocate space for new arguments. */
987         if ((*argvp = nargv = malloc((argc + 1) * sizeof(char *))) == NULL ||
988             (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
989                 err(X_STARTUP, "malloc new args");
990
991         *nargv++ = *argv;
992         argv += 2;
993
994         for (flags = 0; *ap; ++ap) {
995                 switch (*ap) {
996                 case 'B':
997                 case 'b':
998                 case 'd':
999                 case 'e':
1000                 case 'f':
1001                 case 'F':
1002                 case 'h':
1003                 case 'L':
1004                 case 'Q':
1005                 case 's':
1006                 case 'T':
1007                         if (*argv == NULL) {
1008                                 warnx("option requires an argument -- %c", *ap);
1009                                 usage();
1010                         }
1011                         if ((nargv[0] = malloc(strlen(*argv) + 2 + 1)) == NULL)
1012                                 err(X_STARTUP, "malloc arg");
1013                         nargv[0][0] = '-';
1014                         nargv[0][1] = *ap;
1015                         (void)strcpy(&nargv[0][2], *argv);
1016                         ++argv;
1017                         ++nargv;
1018                         break;
1019                 default:
1020                         if (!flags) {
1021                                 *p++ = '-';
1022                                 flags = 1;
1023                         }
1024                         *p++ = *ap;
1025                         break;
1026                 }
1027         }
1028
1029         /* Terminate flags. */
1030         if (flags) {
1031                 *p = '\0';
1032                 *nargv++ = flagsp;
1033         }
1034
1035         /* Copy remaining arguments. */
1036         while ((*nargv++ = *argv++));
1037
1038         /* Update argument count. */
1039         *argcp = nargv - *argvp - 1;
1040 }