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