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