Imported Upstream version 2.5.1
[debian/amanda] / client-src / calcsize.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1998 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /* 
27  * $Id: calcsize.c,v 1.44 2006/07/25 18:27:56 martinea Exp $
28  *
29  * traverse directory tree to get backup size estimates
30  *
31  * argv[0] is the calcsize program name
32  * argv[1] is the config name or NOCONFIG
33  */
34 #include "amanda.h"
35 #include "statfs.h"
36 #include "version.h"
37 #include "sl.h"
38 #include "util.h"
39
40 #define ROUND(n,x)      ((x) + (n) - 1 - (((x) + (n) - 1) % (n)))
41
42 /*
43 static off_t
44 round_function(n, x)
45     off_t       n,
46     off_t       x)
47 {
48   unsigned long remainder = x % n;
49   if (remainder)
50     x += n - remainder;
51   return x;
52 }
53 */
54
55 #define ST_BLOCKS(s)                                                           \
56             (((((off_t)(s).st_blocks * (off_t)512) <= (s).st_size)) ?          \
57               ((off_t)(s).st_blocks + (off_t)1) :                              \
58               ((s).st_size / (off_t)512 +                                      \
59                 (off_t)((((s).st_size % (off_t)512) != (off_t)0) ?             \
60                 (off_t)1 : (off_t)0)))
61
62 #define FILETYPES       (S_IFREG|S_IFLNK|S_IFDIR)
63
64 typedef struct name_s {
65     struct name_s *next;
66     char *str;
67 } Name;
68
69 Name *name_stack;
70
71 #define MAXDUMPS 10
72
73 struct {
74     int max_inode;
75     int total_dirs;
76     int total_files;
77     off_t total_size;
78     off_t total_size_name;
79 } dumpstats[MAXDUMPS];
80
81 time_t dumpdate[MAXDUMPS];
82 int  dumplevel[MAXDUMPS];
83 int ndumps;
84
85 void (*add_file_name)(int, char *);
86 void (*add_file)(int, struct stat *);
87 off_t (*final_size)(int, char *);
88
89
90 int main(int, char **);
91 void traverse_dirs(char *, char *);
92
93
94 void add_file_name_dump(int, char *);
95 void add_file_dump(int, struct stat *);
96 off_t final_size_dump(int, char *);
97
98 void add_file_name_star(int, char *);
99 void add_file_star(int, struct stat *);
100 off_t final_size_star(int, char *);
101
102 void add_file_name_gnutar(int, char *);
103 void add_file_gnutar(int, struct stat *);
104 off_t final_size_gnutar(int, char *);
105
106 void add_file_name_unknown(int, char *);
107 void add_file_unknown(int, struct stat *);
108 off_t final_size_unknown(int, char *);
109
110 sl_t *calc_load_file(char *filename);
111 int calc_check_exclude(char *filename);
112
113 int use_star_excl = 0;
114 int use_gtar_excl = 0;
115 sl_t *include_sl=NULL, *exclude_sl=NULL;
116
117 int
118 main(
119     int         argc,
120     char **     argv)
121 {
122 #ifdef TEST
123 /* standalone test to ckeck wether the calculated file size is ok */
124     struct stat finfo;
125     int i;
126     off_t dump_total = (off_t)0;
127     off_t gtar_total = (off_t)0;
128     char *d;
129     int l, w;
130
131     safe_fd(-1, 0);
132
133     set_pname("calcsize");
134
135     dbopen(NULL);
136
137     /* Don't die when child closes pipe */
138     signal(SIGPIPE, SIG_IGN);
139
140     if (argc < 2) {
141         fprintf(stderr,"Usage: %s file[s]\n",argv[0]);
142         return 1;
143     }
144     for(i=1; i<argc; i++) {
145         if(lstat(argv[i], &finfo) == -1) {
146             fprintf(stderr, "%s: %s\n", argv[i], strerror(errno));
147             continue;
148         }
149         printf("%s: st_size=%lu", argv[i],(unsigned long)finfo.st_size);
150         printf(": blocks=%llu\n", ST_BLOCKS(finfo));
151         dump_total += (ST_BLOCKS(finfo) + (off_t)1) / (off_t)2 + (off_t)1;
152         gtar_total += ROUND(4,(ST_BLOCKS(finfo) + (off_t)1));
153     }
154     printf("           gtar           dump\n");
155     printf("total      %-9lu         %-9lu\n",gtar_total,dump_total);
156     return 0;
157 #else
158     int i;
159     char *dirname=NULL, *amname=NULL, *filename=NULL, *qfilename = NULL;
160     unsigned long malloc_hist_1, malloc_size_1;
161     unsigned long malloc_hist_2, malloc_size_2;
162
163     safe_fd(-1, 0);
164     safe_cd();
165
166     set_pname("calcsize");
167
168     dbopen(DBG_SUBDIR_CLIENT);
169     dbprintf(("%s: version %s\n", debug_prefix(NULL), version()));
170
171     malloc_size_1 = malloc_inuse(&malloc_hist_1);
172
173 #if 0
174     erroutput_type = (ERR_INTERACTIVE|ERR_SYSLOG);
175 #endif
176
177     argc--, argv++;     /* skip program name */
178
179     /* need at least program, amname, and directory name */
180
181     if(argc < 4) {
182         error("Usage: %s config [DUMP|GNUTAR] name dir [-X exclude-file] [-I include-file] [level date]*",
183               get_pname());
184         /*NOTREACHED*/
185     }
186
187     dbprintf(("config: %s\n", *argv));
188     if (strcmp(*argv, "NOCONFIG") != 0) {
189         dbrename(*argv, DBG_SUBDIR_CLIENT);
190     }
191     argc--;
192     argv++;
193
194     /* parse backup program name */
195
196     if(strcmp(*argv, "DUMP") == 0) {
197 #if !defined(DUMP) && !defined(XFSDUMP)
198         error("dump not available on this system");
199         /*NOTREACHED*/
200 #else
201         add_file_name = add_file_name_dump;
202         add_file = add_file_dump;
203         final_size = final_size_dump;
204 #endif
205     }
206     else if(strcmp(*argv, "GNUTAR") == 0) {
207 #ifndef GNUTAR
208         error("gnutar not available on this system");
209         /*NOTREACHED*/
210 #else
211         add_file_name = add_file_name_gnutar;
212         add_file = add_file_gnutar;
213         final_size = final_size_gnutar;
214         use_gtar_excl++;
215 #endif
216     }
217     else {
218         add_file_name = add_file_name_unknown;
219         add_file = add_file_unknown;
220         final_size = final_size_unknown;
221     }
222     argc--, argv++;
223
224     /* the amanda name can be different from the directory name */
225
226     if (argc > 0) {
227         amname = *argv;
228         argc--, argv++;
229     } else {
230         error("missing <name>");
231         /*NOTREACHED*/
232     }
233
234     /* the toplevel directory name to search from */
235     if (argc > 0) {
236         dirname = *argv;
237         argc--, argv++;
238     } else {
239         error("missing <dir>");
240         /*NOTREACHED*/
241     }
242
243     if ((argc > 1) && strcmp(*argv,"-X") == 0) {
244         argv++;
245
246         if (!(use_gtar_excl || use_star_excl)) {
247           error("exclusion specification not supported");
248           /*NOTREACHED*/
249         }
250         
251         filename = stralloc(*argv);
252         qfilename = quote_string(filename);
253         if (access(filename, R_OK) != 0) {
254             fprintf(stderr,"Cannot open exclude file %s\n", qfilename);
255             use_gtar_excl = use_star_excl = 0;
256         } else {
257             exclude_sl = calc_load_file(filename);
258             if (!exclude_sl) {
259                 fprintf(stderr,"Cannot open exclude file %s: %s\n", qfilename,
260                         strerror(errno));
261                 use_gtar_excl = use_star_excl = 0;
262             }
263         }
264         amfree(qfilename);
265         amfree(filename);
266         argc -= 2;
267         argv++;
268     } else {
269         use_gtar_excl = use_star_excl = 0;
270     }
271
272     if ((argc > 1) && strcmp(*argv,"-I") == 0) {
273         argv++;
274         
275         filename = stralloc(*argv);
276         qfilename = quote_string(filename);
277         if (access(filename, R_OK) != 0) {
278             fprintf(stderr,"Cannot open include file %s\n", qfilename);
279             use_gtar_excl = use_star_excl = 0;
280         } else {
281             include_sl = calc_load_file(filename);
282             if (!include_sl) {
283                 fprintf(stderr,"Cannot open include file %s: %s\n", qfilename,
284                         strerror(errno));
285                 use_gtar_excl = use_star_excl = 0;
286             }
287         }
288         amfree(qfilename);
289         amfree(filename);
290         argc -= 2;
291         argv++;
292     }
293
294     /* the dump levels to calculate sizes for */
295
296     ndumps = 0;
297     while(argc >= 2) {
298         if(ndumps < MAXDUMPS) {
299             dumplevel[ndumps] = atoi(argv[0]);
300             dumpdate [ndumps] = (time_t) atol(argv[1]);
301             ndumps++;
302             argc -= 2, argv += 2;
303         }
304     }
305
306     if(argc) {
307         error("leftover arg \"%s\", expected <level> and <date>", *argv);
308         /*NOTREACHED*/
309     }
310
311     if(is_empty_sl(include_sl)) {
312         traverse_dirs(dirname,".");
313     }
314     else {
315         sle_t *an_include = include_sl->first;
316         while(an_include != NULL) {
317 /*
318             char *adirname = stralloc2(dirname, an_include->name+1);
319             traverse_dirs(adirname);
320             amfree(adirname);
321 */
322             traverse_dirs(dirname, an_include->name);
323             an_include = an_include->next;
324         }
325     }
326     for(i = 0; i < ndumps; i++) {
327
328         amflock(1, "size");
329
330         if (fseek(stderr, 0L, SEEK_END) < 0) {
331             dbprintf(("calcsize: warning - seek failed: %s\n",
332                       strerror(errno)));
333         }
334
335         dbprintf(("calcsize: %s %d SIZE " OFF_T_FMT "\n",
336                amname, dumplevel[i],
337                (OFF_T_FMT_TYPE)final_size(i, dirname)));
338         fprintf(stderr, "%s %d SIZE " OFF_T_FMT "\n",
339                amname, dumplevel[i],
340                (OFF_T_FMT_TYPE)final_size(i, dirname));
341         fflush(stderr);
342
343         amfunlock(1, "size");
344     }
345
346     malloc_size_2 = malloc_inuse(&malloc_hist_2);
347
348     if(malloc_size_1 != malloc_size_2) {
349         malloc_list(fileno(stderr), malloc_hist_1, malloc_hist_2);
350     }
351
352     return 0;
353 #endif
354 }
355
356 /*
357  * =========================================================================
358  */
359
360 #if !defined(HAVE_BASENAME) && defined(BUILTIN_EXCLUDE_SUPPORT)
361
362 static char *
363 basename(
364     char *      file)
365 {
366     char *cp;
367
368     if ( (cp = strrchr(file,'/')) )
369         return cp+1;
370     return file;
371 }
372 #endif
373
374 void push_name(char *str);
375 char *pop_name(void);
376
377 void
378 traverse_dirs(
379     char *      parent_dir,
380     char *      include)
381 {
382     DIR *d;
383     struct dirent *f;
384     struct stat finfo;
385     char *dirname, *newname = NULL;
386     char *newbase = NULL;
387     dev_t parent_dev = (dev_t)0;
388     int i;
389     size_t l;
390     size_t parent_len;
391     int has_exclude;
392     char *aparent;
393
394     if(parent_dir == NULL || include == NULL)
395         return;
396
397     has_exclude = !is_empty_sl(exclude_sl) && (use_gtar_excl || use_star_excl);
398     aparent = vstralloc(parent_dir, "/", include, NULL);
399
400     if(stat(parent_dir, &finfo) != -1)
401         parent_dev = finfo.st_dev;
402
403     parent_len = strlen(parent_dir);
404
405     push_name(aparent);
406
407     for(; (dirname = pop_name()) != NULL; free(dirname)) {
408         if(has_exclude && calc_check_exclude(dirname+parent_len+1)) {
409             continue;
410         }
411         if((d = opendir(dirname)) == NULL) {
412             perror(dirname);
413             continue;
414         }
415
416         l = strlen(dirname);
417         if(l > 0 && dirname[l - 1] != '/') {
418             newbase = newstralloc2(newbase, dirname, "/");
419         } else {
420             newbase = newstralloc(newbase, dirname);
421         }
422
423         while((f = readdir(d)) != NULL) {
424             int is_symlink = 0;
425             int is_dir;
426             int is_file;
427             if(is_dot_or_dotdot(f->d_name)) {
428                 continue;
429             }
430
431             newname = newstralloc2(newname, newbase, f->d_name);
432             if(lstat(newname, &finfo) == -1) {
433                 fprintf(stderr, "%s/%s: %s\n",
434                         dirname, f->d_name, strerror(errno));
435                 continue;
436             }
437
438             if(finfo.st_dev != parent_dev)
439                 continue;
440
441 #ifdef S_IFLNK
442             is_symlink = ((finfo.st_mode & S_IFMT) == S_IFLNK);
443 #endif
444             is_dir = ((finfo.st_mode & S_IFMT) == S_IFDIR);
445             is_file = ((finfo.st_mode & S_IFMT) == S_IFREG);
446
447             if (!(is_file || is_dir || is_symlink)) {
448                 continue;
449             }
450
451             {
452                 int is_excluded = -1;
453                 for(i = 0; i < ndumps; i++) {
454                     add_file_name(i, newname);
455                     if(is_file && (time_t)finfo.st_ctime >= dumpdate[i]) {
456
457                         if(has_exclude) {
458                             if(is_excluded == -1)
459                                 is_excluded =
460                                        calc_check_exclude(newname+parent_len+1);
461                             if(is_excluded == 1) {
462                                 i = ndumps;
463                                 continue;
464                             }
465                         }
466                         add_file(i, &finfo);
467                     }
468                 }
469                 if(is_dir) {
470                     if(has_exclude && calc_check_exclude(newname+parent_len+1))
471                         continue;
472                     push_name(newname);
473                 }
474             }
475         }
476
477 #ifdef CLOSEDIR_VOID
478         closedir(d);
479 #else
480         if(closedir(d) == -1)
481             perror(dirname);
482 #endif
483     }
484     amfree(newbase);
485     amfree(newname);
486     amfree(aparent);
487 }
488
489 void
490 push_name(
491     char *      str)
492 {
493     Name *newp;
494
495     newp = alloc(SIZEOF(*newp));
496     newp->str = stralloc(str);
497
498     newp->next = name_stack;
499     name_stack = newp;
500 }
501
502 char *
503 pop_name(void)
504 {
505     Name *newp = name_stack;
506     char *str;
507
508     if(!newp) return NULL;
509
510     name_stack = newp->next;
511     str = newp->str;
512     amfree(newp);
513     return str;
514 }
515
516
517 /*
518  * =========================================================================
519  * Backup size calculations for DUMP program
520  *
521  * Given the system-dependent nature of dump, it's impossible to pin this
522  * down accurately.  Luckily, that's not necessary.
523  *
524  * Dump rounds each file up to TP_BSIZE bytes, which is 1k in the BSD dump,
525  * others are unknown.  In addition, dump stores three bitmaps at the
526  * beginning of the dump: a used inode map, a dumped dir map, and a dumped
527  * inode map.  These are sized by the number of inodes in the filesystem.
528  *
529  * We don't take into account the complexities of BSD dump's indirect block
530  * requirements for files with holes, nor the dumping of directories that
531  * are not themselves modified.
532  */
533 void
534 add_file_name_dump(
535     int         level,
536     char *      name)
537 {
538     (void)level;        /* Quiet unused parameter warning */
539     (void)name;         /* Quiet unused parameter warning */
540
541     return;
542 }
543
544 void
545 add_file_dump(
546     int                 level,
547     struct stat *       sp)
548 {
549     /* keep the size in kbytes, rounded up, plus a 1k header block */
550     if((sp->st_mode & S_IFMT) == S_IFREG || (sp->st_mode & S_IFMT) == S_IFDIR)
551         dumpstats[level].total_size +=
552                         (ST_BLOCKS(*sp) + (off_t)1) / (off_t)2 + (off_t)1;
553 }
554
555 off_t
556 final_size_dump(
557     int         level,
558     char *      topdir)
559 {
560     generic_fs_stats_t stats;
561     off_t mapsize;
562     char *s;
563
564     /* calculate the map sizes */
565
566     s = stralloc2(topdir, "/.");
567     if(get_fs_stats(s, &stats) == -1) {
568         error("statfs %s: %s", s, strerror(errno));
569         /*NOTREACHED*/
570     }
571     amfree(s);
572
573     mapsize = (stats.files + (off_t)7) / (off_t)8;    /* in bytes */
574     mapsize = (mapsize + (off_t)1023) / (off_t)1024;  /* in kbytes */
575
576     /* the dump contains three maps plus the files */
577
578     return (mapsize * (off_t)3) + dumpstats[level].total_size;
579 }
580
581 /*
582  * =========================================================================
583  * Backup size calculations for GNUTAR program
584  *
585  * Gnutar's basic blocksize is 512 bytes.  Each file is rounded up to that
586  * size, plus one header block.  Gnutar stores directories' file lists in
587  * incremental dumps - we'll pick up size of the modified dirs here.  These
588  * will be larger than a simple filelist of their contents, but that's ok.
589  *
590  * As with DUMP, we only need a reasonable estimate, not an exact figure.
591  */
592 void
593 add_file_name_gnutar(
594     int         level,
595     char *      name)
596 {
597     (void)name; /* Quiet unused parameter warning */
598
599 /*  dumpstats[level].total_size_name += strlen(name) + 64;*/
600     dumpstats[level].total_size += (off_t)1;
601 }
602
603 void
604 add_file_gnutar(
605     int                 level,
606     struct stat *       sp)
607 {
608     /* the header takes one additional block */
609     dumpstats[level].total_size += ST_BLOCKS(*sp);
610 }
611
612 off_t
613 final_size_gnutar(
614     int         level,
615     char *      topdir)
616 {
617     (void)topdir;       /* Quiet unused parameter warning */
618
619     /* divide by two to get kbytes, rounded up */
620     /* + 4 blocks for security */
621     return (dumpstats[level].total_size + (off_t)5 +
622                 (dumpstats[level].total_size_name/(off_t)512)) / (off_t)2;
623 }
624
625 /*
626  * =========================================================================
627  * Backup size calculations for unknown backup programs.
628  *
629  * Here we'll just add up the file sizes and output that.
630  */
631
632 void
633 add_file_name_unknown(
634     int         level,
635     char *      name)
636 {
637     (void)level;        /* Quiet unused parameter warning */
638     (void)name;         /* Quiet unused parameter warning */
639
640     return;
641 }
642
643 void
644 add_file_unknown(
645     int                 level,
646     struct stat *       sp)
647 {
648     /* just add up the block counts */
649     if((sp->st_mode & S_IFMT) == S_IFREG || (sp->st_mode & S_IFMT) == S_IFDIR)
650         dumpstats[level].total_size += ST_BLOCKS(*sp);
651 }
652
653 off_t
654 final_size_unknown(
655     int         level,
656     char *      topdir)
657 {
658     (void)topdir;       /* Quiet unused parameter warning */
659
660     /* divide by two to get kbytes, rounded up */
661     return (dumpstats[level].total_size + (off_t)1) / (off_t)2;
662 }
663
664 /*
665  * =========================================================================
666  */
667 sl_t *
668 calc_load_file(
669     char *      filename)
670 {
671     char pattern[1025];
672
673     sl_t *sl_list;
674
675     FILE *file = fopen(filename, "r");
676
677     if (!file) {
678         return NULL;
679     }
680
681     sl_list = new_sl();
682
683     while(fgets(pattern, 1025, file)) {
684         if(strlen(pattern)>0 && pattern[strlen(pattern)-1] == '\n')
685             pattern[strlen(pattern)-1] = '\0';
686         sl_list = append_sl(sl_list, pattern);
687     }  
688     fclose(file);
689
690     return sl_list;
691 }
692
693 int
694 calc_check_exclude(
695     char *      filename)
696 {
697     sle_t *an_exclude;
698     if(is_empty_sl(exclude_sl)) return 0;
699
700     an_exclude=exclude_sl->first;
701     while(an_exclude != NULL) {
702         if(match_tar(an_exclude->name, filename)) {
703             return 1;
704         }
705         an_exclude=an_exclude->next;
706     }
707     return 0;
708 }