dbackup 42.7 KB
Newer Older
Nigel Kukard's avatar
Nigel Kukard committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/perl -w
# Copyright (c) 2010-2012, AllWorldIT
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Author: Nigel Kukard <nkukard@lbsd.net>


# TODO:
# - USE incremental backups!!!! fucking awesome
23
24
25
26
#
# - Read in defaultSystemExcl extras from /proc/mounts
# - proc, nfs, nfs4, fusectl fuse.glusterfs, sysfs, tmpfs, devtmpfs, devpts
#
Nigel Kukard's avatar
Nigel Kukard committed
27
28
29
30


use strict;
use Compress::Zlib;
31
use Config::IniFiles;
Nigel Kukard's avatar
Nigel Kukard committed
32
33
34
35
36
37
use Cwd;
use Fcntl qw (:mode);
use File::Find;
use File::Path qw( rmtree mkpath );
use File::Spec;
use Getopt::Long;
38
use POSIX qw (strftime lchown);
Nigel Kukard's avatar
Nigel Kukard committed
39
40
41
42
43
use Data::Dumper;
use MIME::Base64;



Nigel Kukard's avatar
Nigel Kukard committed
44
my $VERSION = "0.0.15";
Nigel Kukard's avatar
Nigel Kukard committed
45
# System dirs we don't care about
46
my @defaultSystemExcl = ("/dev","/run","/proc","/sys","/tmp","/var/tmp","/misc","/media","/mnt");
Nigel Kukard's avatar
Nigel Kukard committed
47
# These should be backed up separately
48
49
50
my @defaultDataExcl = (
		"/var/lib/mysql","/var/lib/pgsql",
		"/var/amavis/tmp/",
51
		"/var/spool/mailman/retry",
52
		"/var/spool/postfix/public",
53
		"/var/spool/postfix/private",
54
		"/var/spool/squid",
55
		"/var/cache/yum"
56
);
Nigel Kukard's avatar
Nigel Kukard committed
57

58

Nigel Kukard's avatar
Nigel Kukard committed
59
# Backup constants
Nigel Kukard's avatar
Nigel Kukard committed
60
use constant {
Nigel Kukard's avatar
Nigel Kukard committed
61
62
	LOG_DEBUG => 5,
	LOG_INFO => 4,
Nigel Kukard's avatar
Nigel Kukard committed
63
	LOG_NOTICE => 3,
Nigel Kukard's avatar
Nigel Kukard committed
64
65
	LOG_WARNING => 2,
	LOG_ERROR => 1
Nigel Kukard's avatar
Nigel Kukard committed
66
67
};

Nigel Kukard's avatar
Nigel Kukard committed
68
69
70
71
72
73
74
75
76
77
use constant {
	ST_FILE_CHANGED 	=> 1,
	ST_DIR_NEW	=> 2,
	ST_DIR_SYS	=> 4,
	ST_DIR_CHANGED	=> 8,
	ST_FILE_ATTR_CHANGED	=> 16,
	ST_FILE_NEW	=> 32,
};


78
79
80
# Main config
my %config = (
		'log-level' => LOG_NOTICE,
81
		'tar' => 'tar',
82
		'exclude-system' => 0,
Nigel Kukard's avatar
Nigel Kukard committed
83
		'backup-upgrade' => 0,
84
85
86
87
88
89
90
91
92
93
94
95
);
# Choose default compression method
if (-x "/bin/xz" || -x "/usr/bin/xz") {
	$config{'compress'} = "xz";
} else {
	$config{'compress'} = "bzip2";
}





Nigel Kukard's avatar
Nigel Kukard committed
96
97
98
99
100
101
102
103
104

print(STDERR "DBackup v$VERSION, Copyright (c) 2010-2012, AllWorldIT\n\n");


# Grab options
my %optctl = ();
GetOptions(\%optctl,
	"help",

105
	"config=s",
Nigel Kukard's avatar
Nigel Kukard committed
106
	"log-level=i",
107
	"tar=s",
Nigel Kukard's avatar
Nigel Kukard committed
108
	"manifest-format=s",
109

Nigel Kukard's avatar
Nigel Kukard committed
110
	"backup",
Nigel Kukard's avatar
Nigel Kukard committed
111
	"backup-upgrade",
Nigel Kukard's avatar
Nigel Kukard committed
112
113
	"compress:s",
	"exclude-system",
114
115
	"system-base=s@",
	"system-dir=s@",
Nigel Kukard's avatar
Nigel Kukard committed
116

117
118
	"tar-ignore-failed-read=s@",

Nigel Kukard's avatar
Nigel Kukard committed
119
	"exclude-data",
120
	"data-dir=s@",
121
	
122
123
	"exclude-file=s@",
	"exclude-path=s@",
Nigel Kukard's avatar
Nigel Kukard committed
124

125
126
	"exclude-fs-type=s@",

Nigel Kukard's avatar
Nigel Kukard committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
	"restore",
	"tar-keep-newer",
	"tar-keep-old-files",
);

# Check for help
if (defined($optctl{'help'})) {
	displayHelp();
	exit 0;
}

# Check for invalid combination
if (defined($optctl{'backup'}) && defined($optctl{'restore'})) {
	print(STDERR "ERROR: Cannot backup AND restore at the same time\n\n");
	displayHelp();
	exit 1;
}

# Make sure we only have 2 additional args
if (@ARGV > 2 || @ARGV < 2) {
		print(STDERR "ERROR: Invalid number of arguments\n\n");
		displayHelp();
		exit 1;
}

# Check both dirs exist...
if (! -d $ARGV[0]) {
	print(STDERR "ERROR: Source directory '".$ARGV[0]."' does not exist!\n\n");
	exit 1;
}
if (! -d $ARGV[1]) {
	print(STDERR "ERROR: Destination directory '".$ARGV[1]."' does not exist!\n\n");
	exit 1;
}

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# Check config file exists
if (defined($optctl{'config'})) {
	if (! -f $optctl{'config'}) {
		print(STDERR "ERROR: Configuration file '".$optctl{'config'}."' NOT found!\n");
		exit 1;
	}

	# Use config file, ignore case
	tie my %inifile, 'Config::IniFiles', (
			-file => $optctl{'config'},
			-nocase => 1
	) or die "Failed to open config file '".$optctl{'config'}."': ".join("\n",@Config::IniFiles::errors);

	# Check if we actually have something...
	if (defined($inifile{'backup'})) {
		# Loop with config items
		foreach my $item (keys %{$inifile{'backup'}}) {
			$config{$item} = $inifile{'backup'}{$item};
		}
	}
}


185
186
187
#
# Process config
#
188
if (!defined($config{'system-base'})) {
189
	# Quick hack to see if we have a cmdline option
190
191
	if (!defined($optctl{'system-base'})) {
		$config{'system-base'} = ["/"];
192
	} else {
193
		$config{'system-base'} = [];
194
195
	}
} else {
196
197
198
199
200
201
202
	$config{'system-base'} = toArray($config{'system-base'});
}

if (!defined($config{'system-dir'})) {
	$config{'system-dir'} = [];
} else {
	$config{'system-dir'} = toArray($config{'system-dir'});
203
204
}

205
206
207
208
209
210
if (!defined($config{'tar-ignore-failed-read'})) {
	$config{'tar-ignore-failed-read'} = [];
} else {
	$config{'tar-ignore-failed-read'} = toArray($config{'tar-ignore-failed-read'});
}

211
212
if (!defined($config{'data-dir'})) {
	$config{'data-dir'} = [];
213
} else {
214
	$config{'data-dir'} = toArray($config{'data-dir'});
215
216
}

217
218
if (!defined($config{'exclude-file'})) {
	$config{'exclude-file'} = [];
219
} else {
220
	$config{'exclude-file'} = toArray($config{'exclude-file'});
221
222
}

223
224
if (!defined($config{'exclude-path'})) {
	$config{'exclude-path'} = [];
225
} else {
226
	$config{'exclude-path'} = toArray($config{'exclude-path'});
227
228
}

229
230
231
232
233
234
235
236
237
238
if (!defined($config{'exclude-fs-type'})) {
	$config{'exclude-fs-type'} = [];
} else {
	$config{'exclude-fs-type'} = toArray($config{'exclude-fs-type'});
}


#
# Check commandline options
#
239

Nigel Kukard's avatar
Nigel Kukard committed
240
241
242
243
if (defined($optctl{'backup-upgrade'})) {
	$config{'backup-upgrade'} = 1;
}

Nigel Kukard's avatar
Nigel Kukard committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
if (defined($optctl{'compress'})) {
	# Why use --compress with --restore?
	if (defined($optctl{'restore'})) {
		print(STDERR "WARNING: The use of --compress with --restore does not make sense\n");
	}

	# Make sure its valid
	if (
				$optctl{'compress'} ne "xz" &&
				$optctl{'compress'} ne "bzip2" &&
				$optctl{'compress'} ne "gzip" &&
				$optctl{'compress'} ne "none"
	) {	
		print(STDERR "ERROR: Compression is invalid, valid values are: xz bzip2 gzip none\n\n");
		displayHelp();
		exit 1;
	}
261
	$config{'compress'} = $optctl{'compress'};
Nigel Kukard's avatar
Nigel Kukard committed
262
263
}

264
265
266
267
268
269
270
271
272
273
if (defined($optctl{'tar'})) {
	# Check if tar is executable
	if ( -x $optctl{'tar'}) {
		$config{'tar'} = $optctl{'tar'};
	} else {
		print(STDERR "ERROR: tar '".$optctl{'tar'}."' does not exist or is not executable\n");
	}
}
my $tarVer = getTarVer($config{'tar'});

274
275
276
if (defined($optctl{'log-level'})) {
	$config{'log-level'} = $optctl{'log-level'};
}
277

Nigel Kukard's avatar
Nigel Kukard committed
278
279
280
281
282
283
284
285
286
287
288
289
if (defined($optctl{'manifest-format'})) {
	if (
				$optctl{'manifest-format'} ne "null" &&
				$optctl{'manifest-format'} ne "newline"
	) {	
		print(STDERR "ERROR: Manifest format is invalid, valid values are: null newline\n\n");
		displayHelp();
		exit 1;
	}
	$config{'manifest-format'} = $optctl{'manifest-format'};
}

290
291
292
if (defined($optctl{'exclude-system'})) {
	$config{'exclude-system'} = 1;
}
293

294
295
if (defined($optctl{'system-base'})) {
	push(@{$config{'system-base'}},@{$optctl{'system-base'}});
Nigel Kukard's avatar
Nigel Kukard committed
296
}
297

298
299
if (defined($optctl{'system-dir'})) {
	push(@{$config{'system-dir'}},@{$optctl{'system-dir'}});
Nigel Kukard's avatar
Nigel Kukard committed
300
}
301

302
303
304
305
if (defined($optctl{'tar-ignore-failed-read'})) {
	push(@{$config{'tar-ignore-failed-read'}},@{$optctl{'tar-ignore-failed-read'}});
}

306
307
if (defined($optctl{'data-dir'})) {
	push(@{$config{'data-dir'}},@{$optctl{'data-dir'}});
308
}
309

310
311
312
if (defined($optctl{'exclude-file'})) {
	push(@{$config{'exclude-file'}},@{$optctl{'exclude-file'}});
}
313

314
315
if (defined($optctl{'exclude-path'})) {
	push(@{$config{'exclude-path'}},@{$optctl{'exclude-path'}});
Nigel Kukard's avatar
Nigel Kukard committed
316
317
}

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
if (defined($optctl{'exclude-fs-type'})) {
	push(@{$config{'exclude-fs-type'}},@{$optctl{'exclude-fs-type'}});
}

if (@{$config{'exclude-fs-type'}} > 0) {
	# Pull in mounts
	open(MOUNTS, "< /proc/mounts")
			or die "ERROR: Failed to open '/proc/mounts': $!";
	while (my $line = <MOUNTS>) {
		chomp($line);
		# Split off items we need
		my (undef,$path,$type) = split(/\s+/,$line);
		# Loop with types and check
		foreach my $item (@{$config{'exclude-fs-type'}}) {
			if ($item eq $type) {
				push(@{$config{'exclude-path'}},$path);
			}
		}
	}
	close(MOUNTS);
}

Nigel Kukard's avatar
Nigel Kukard committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Sanitize the source and dest
my $sourceDir = File::Spec->rel2abs($ARGV[0]);
my $destDir = File::Spec->rel2abs($ARGV[1]);


# Backup function
sub backup
{
	our ($source,$dest) = @_;


	# State infor for current dir
	our %doBackup;
	our %srcFileList;
	our %srcDirList;
	# Original .state file read in during backup
	our %origFileList;
	our %origDirList;
	our %origPathAttribs;
	# New attributes
	our %newPathAttribs;


	# Preprocess dir
	sub backup_preprocess {
		my @list = @_;

		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Check if this dir should be backed up or not....
		if ( -f "$source/$path/.nodbackup" ) {
Nigel Kukard's avatar
Nigel Kukard committed
372
			printLog(LOG_INFO,"S: Path '[$source]/($path)' EXCLUDED from backup with .nodbackup\n");
Nigel Kukard's avatar
Nigel Kukard committed
373
374
375
376
			return ();
		}
		# Exclude trash folders
		if ( "$source/$path" =~ /(\.Trash-[0-9]{4})$/) {
Nigel Kukard's avatar
Nigel Kukard committed
377
			printLog(LOG_INFO,"S: Path '[$source]/($path)' EXCLUDED from backup, Linux trash folder\n");
Nigel Kukard's avatar
Nigel Kukard committed
378
379
380
381
382
383
384
385
386
387
			return ();
		}

		# Make sure even if we processing empty dirs that we actually record it
		if (!defined($srcFileList{$path})) {
			# Just set to empty hash ref
			$srcFileList{$path} = {};
		}

		# Exclude system directories
388
		if ($config{'exclude-system'}) {
Nigel Kukard's avatar
Nigel Kukard committed
389
			# Loop through system dirs
390
			foreach my $sysdir (@{$config{'system-base'}}) {
Nigel Kukard's avatar
Nigel Kukard committed
391
				# Loop with system paths
392
				foreach my $excl (@defaultSystemExcl,@{$config{'system-dir'}}) {
Nigel Kukard's avatar
Nigel Kukard committed
393
					# Sanitize path
394
					my $testPath = File::Spec->rel2abs("$sysdir/$excl");
Nigel Kukard's avatar
Nigel Kukard committed
395
					# Check...
396
					if ("/$path" eq $testPath) {
Nigel Kukard's avatar
Nigel Kukard committed
397
						printLog(LOG_INFO,"S: Path '[$source]/($path)' is a system directory, ignoring files\n");
Nigel Kukard's avatar
Nigel Kukard committed
398
399
400
401
402
						$doBackup{$path} |= ST_DIR_SYS;
						return ();
					}
				}
				# Check if we excluding data dirs
403
				if (defined($config{'exclude-data'})) {
Nigel Kukard's avatar
Nigel Kukard committed
404
					# Loop with data dirs
405
					foreach my $excl (@defaultDataExcl,@{$config{'data-dir'}}) {
Nigel Kukard's avatar
Nigel Kukard committed
406
						# Sanitize path
407
						my $testPath = File::Spec->rel2abs("$sysdir/$excl");
Nigel Kukard's avatar
Nigel Kukard committed
408
						# Check...
409
						if ("/$path" eq $testPath) {
Nigel Kukard's avatar
Nigel Kukard committed
410
							printLog(LOG_INFO,"S: Path '[$source]/($path)' is a data directory, ignoring files\n");
Nigel Kukard's avatar
Nigel Kukard committed
411
412
413
414
415
416
417
							$doBackup{$path} |= ST_DIR_SYS;
							return ();
						}
					}
				}
			}
		}
418
419
420
421
		# Exclude paths
		foreach my $item (@{$config{'exclude-path'}}) {
			# Check...
			if ("/$path" =~ $item) {
Nigel Kukard's avatar
Nigel Kukard committed
422
				printLog(LOG_INFO,"S: Path '[$source]/($path)' is an excluded path, ignoring files\n");
423
424
425
426
				$doBackup{$path} |= ST_DIR_SYS;
				return ();
			}
		}
Nigel Kukard's avatar
Nigel Kukard committed
427
428
429
430
431
432
433
434

		# Check if this dir exists on the backup, if not we need to back it up obviously...
		if ( ! -d "$dest/$path") {
			$doBackup{$path} |= ST_DIR_NEW;
		# This can probably only be because a backup was continued
		} elsif ( ! -f "$dest/$path/.dbackup-state" ) {
			# First backup will never have the main dir .dbackup-state file existing
			if ($path ne "") {
Nigel Kukard's avatar
Nigel Kukard committed
435
				printLog(LOG_WARNING,"State file '[$dest]/($path)/.dbackup-state' does not exist\n");
Nigel Kukard's avatar
Nigel Kukard committed
436
437
438
439
440
441
442
443
444
445
446
			}
			$doBackup{$path} |= ST_DIR_NEW;
		}

		# Cannot read in for new dirs can we...
		if (($doBackup{$path} & ST_DIR_NEW) != ST_DIR_NEW) {
			# Load state file
			loadStateFile("$dest/$path/.dbackup-state",$path,\%origFileList,\%origDirList,\%origPathAttribs);

			# Check we have at least the version attribute
			if (!defined($origPathAttribs{$path}) || !defined($origPathAttribs{$path}->{'dbackup.version'})) {
Nigel Kukard's avatar
Nigel Kukard committed
447
				printLog(LOG_ERROR,"No dbackup version information found in '[$dest]/($path)/.dbackup-state', IGNORING\n");
Nigel Kukard's avatar
Nigel Kukard committed
448
449
				delete($origDirList{$path});
				delete($origFileList{$path});
Nigel Kukard's avatar
Nigel Kukard committed
450
451
452
453
454
455
456
457
458
459
460
461

			# NK:
			# Sanity check, some versions created empty'ish .dbackup-state files with no sequence  < 2012-01-21
			# If we have a manifest, we should have a backup, therefore a format and sequence
			} elsif (
					-f "$dest/$path/dbackup0.manifest" && (
						!defined($origPathAttribs{$path}->{'format'}) || 
						!defined($origPathAttribs{$path}->{'sequence'})
					)
			) {
				printLog(LOG_ERROR,"No dbackup format/sequence information found in ".
						"'[$dest]/($path)/.dbackup-state', IGNORING\n");
Nigel Kukard's avatar
Nigel Kukard committed
462
463
				delete($origDirList{$path});
				delete($origFileList{$path});
Nigel Kukard's avatar
Nigel Kukard committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481

			# Check if we going to upgrade...
			} else {
				# Are we doing backup upgrades?
				if ($config{'backup-upgrade'}) {
					# Pull in versions
					my $a = getNumericVer($origPathAttribs{$path}->{'dbackup.version'});
					my $b = getNumericVer($VERSION);
					# Compare
					if ($a < $b) {
						# Check if end in .x
						if ($VERSION =~ /\.x$/) {
							printLog(LOG_WARNING,"S: Path '[$source]/($path)' ".
									"cannot be upgraded, dbackup is TRUNK version\n");
						} else {
							printLog(LOG_INFO,"S: Path '[$source]/($path)' will be backed up, upgrading\n");
							delete($origDirList{$path});
							delete($origFileList{$path});
482
483
							# Force state file update if dir is empty
							$doBackup{$path} |= ST_DIR_CHANGED;
Nigel Kukard's avatar
Nigel Kukard committed
484
485
486
						}
					}
				}
487
488
489
490
			}
		}

		# Apply filter...
491
		if ((@{$config{'exclude-file'}}) > 0) {
492
493
494
495
496
497
			my @newList;
			foreach my $item (@list) {
				my $match = 0;
				# Apply only to files
				if ( -f "$source/$path/$item") {
					# Loop with exclude filters
498
					foreach my $filter (@{$config{'exclude-file'}}) {
499
500
						# Check for match
						if ($item =~ $filter) {
Nigel Kukard's avatar
Nigel Kukard committed
501
							printLog(LOG_INFO,"S: Path '[$source]/($path)/$item' matches file exclude filter, ignoring\n");
502
503
504
505
506
507
508
509
510
511
							# XXX: NK - If this ws backed up before and now not, dir has changed?
							$match = 1;
							last;
						}
					}
				}
				# If not matched, add to new list
				if (!$match) {
					push(@newList,$item);
				}
Nigel Kukard's avatar
Nigel Kukard committed
512
			}
513
514
			# Replace the list now
			@list = @newList;
Nigel Kukard's avatar
Nigel Kukard committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
		}

		return @list;
	}

	# Process files
	sub backup_process {
		my $name = $File::Find::name;
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Store current filename
		my $item = $_;

		# We use lstat so we don't follow symlinks that don't exist
		my @stat = lstat($name);
		# Split it up
		my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,
				$ctime,$blksize,$blocks) = @stat;

		# Process directory
		if (S_ISDIR($mode)) {
			# Skip over main dir
			if ($item eq ".") {
				return;
			}

			# Make sure sub dirs have a santized name
			my $ppath = ($path ne "") ? "$path/$item" : $item;

			# Set default flags to nothing...
			$doBackup{$ppath} = 0;

			# Ok, lets see whats going on with the dir
			if (!defined($origDirList{$path}->{$item})) {
Nigel Kukard's avatar
Nigel Kukard committed
550
				printLog(LOG_DEBUG,"S: Directory '[$source]/($path)/$item' is new\n");
Nigel Kukard's avatar
Nigel Kukard committed
551
552
553
554
555
556
557
				$doBackup{$path} |= ST_DIR_CHANGED;

			# Check if mtime matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'mtime'}) ||
					$origDirList{$path}->{$item}->{'mtime'} ne $mtime
			) {
Nigel Kukard's avatar
Nigel Kukard committed
558
				printLog(LOG_DEBUG,"S: Directory '[$source]/($path)/$item' was modified\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
559
560
561
562
563
564
				$doBackup{$path} |= ST_DIR_CHANGED;
			# Check if uid matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'uid'}) ||
					$origDirList{$path}->{$item}->{'uid'} ne $uid
			) {
Nigel Kukard's avatar
Nigel Kukard committed
565
				printLog(LOG_DEBUG,"S: Directory '[$source]/($path)/$item' UID was changed\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
566
567
568
569
570
571
				$doBackup{$path} |= ST_DIR_CHANGED;
			# Check if gid matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'gid'}) ||
					$origDirList{$path}->{$item}->{'gid'} ne $gid
			) {
Nigel Kukard's avatar
Nigel Kukard committed
572
				printLog(LOG_DEBUG,"S: Directory '[$source]/($path)/$item' GID was changed\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
573
574
575
576
577
578
				$doBackup{$path} |= ST_DIR_CHANGED;
			# Check if mode matches
			} elsif (
					!defined($origDirList{$path}->{$item}->{'mode'}) ||
					$origDirList{$path}->{$item}->{'mode'} ne $mode
			) {
Nigel Kukard's avatar
Nigel Kukard committed
579
				printLog(LOG_DEBUG,"S: Directory '[$source]/($path)/$item' MODE was changed\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
580
581
582
583
584
585
586
587
588
589
590
591
592
				$doBackup{$path} |= ST_DIR_CHANGED;
			}

			# Record details...	
			$srcDirList{$path}->{$item}->{'size'} = $size;
			$srcDirList{$path}->{$item}->{'ctime'} = $ctime;
			$srcDirList{$path}->{$item}->{'atime'} = $atime;
			$srcDirList{$path}->{$item}->{'mtime'} = $mtime;
			$srcDirList{$path}->{$item}->{'uid'} = $uid;
			$srcDirList{$path}->{$item}->{'gid'} = $gid;
			$srcDirList{$path}->{$item}->{'mode'} = $mode;

			return;
593
594
595
596
597

		# Check if we're a socket
		} elsif (S_ISSOCK($mode)) {
			# Blatently ignore...
			return;
Nigel Kukard's avatar
Nigel Kukard committed
598
599
600
601
602
603
604
605
		}

		# Initialize file state
		my $state = 0;

		# Check if file does not exists on backup
		if (!defined($origFileList{$path}->{$item})) {
			if (($doBackup{$path} & ST_DIR_NEW) != ST_DIR_NEW) {
Nigel Kukard's avatar
Nigel Kukard committed
606
				printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' is new\n");
Nigel Kukard's avatar
Nigel Kukard committed
607
608
609
610
611
612
613
614
			}
			$state |= ST_FILE_NEW;

		# Check if size matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'size'}) ||
				$origFileList{$path}->{$item}->{'size'} ne $size
		) {
Nigel Kukard's avatar
Nigel Kukard committed
615
			printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' has different size\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
616
617
618
619
620
621
622
623
624
625
			$state |= ST_FILE_CHANGED;

		#
		# NK: Does not like chmod changes to files???
		#
		# Check if ctime matches
#		} elsif (
#				!defined($origFileList{$path}->{$item}->{'ctime'}) ||
#				$origFileList{$path}->{$item}->{'ctime'} ne $ctime
#		) {
Nigel Kukard's avatar
Nigel Kukard committed
626
#			printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' was recreated\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
627
628
629
630
631
632
633
#			$state |= ST_FILE_CHANGED;

		# Check if mtime matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'mtime'}) ||
				$origFileList{$path}->{$item}->{'mtime'} ne $mtime
		) {
Nigel Kukard's avatar
Nigel Kukard committed
634
			printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' was modified\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
635
636
637
638
639
640
641
			$state |= ST_FILE_CHANGED;

		# Check if uid matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'uid'}) ||
				$origFileList{$path}->{$item}->{'uid'} ne $uid
		) {
Nigel Kukard's avatar
Nigel Kukard committed
642
			printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' UID was changed\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
643
644
645
646
647
648
649
			$state |= ST_FILE_ATTR_CHANGED

		# Check if gid matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'gid'}) ||
				$origFileList{$path}->{$item}->{'gid'} ne $gid
		) {
Nigel Kukard's avatar
Nigel Kukard committed
650
			printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' GID was changed\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
651
652
653
654
655
656
657
			$state |= ST_FILE_ATTR_CHANGED;

		# Check if mode matches
		} elsif (
				!defined($origFileList{$path}->{$item}->{'mode'}) ||
				$origFileList{$path}->{$item}->{'mode'} ne $mode
		) {
Nigel Kukard's avatar
Nigel Kukard committed
658
			printLog(LOG_DEBUG,"S: File '[$source]/($path)/$item' MODE was changed\n"); 
Nigel Kukard's avatar
Nigel Kukard committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
			$state |= ST_FILE_ATTR_CHANGED;
		}

		# Update state of path, this is used below, the $state is used to track WHAT changed
		if ($state) {
			$doBackup{$path} |= ST_FILE_CHANGED;
		}

		# Record details...	
		$srcFileList{$path}->{$item}->{'size'} = $size;
		$srcFileList{$path}->{$item}->{'ctime'} = $ctime;
		$srcFileList{$path}->{$item}->{'atime'} = $atime;
		$srcFileList{$path}->{$item}->{'mtime'} = $mtime;
		$srcFileList{$path}->{$item}->{'uid'} = $uid;
		$srcFileList{$path}->{$item}->{'gid'} = $gid;
		$srcFileList{$path}->{$item}->{'mode'} = $mode;
		$srcFileList{$path}->{$item}->{'_state'} = $state;
	}


	# Time to do stuff
	sub backup_postprocess {
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;
		# Get current lists
		my $curDirList = $srcDirList{$path};
		my $curFileList = $srcFileList{$path};

		# Compare the two file lists, we know what was added, lets see if anything was removed
		foreach my $fname (keys %{$origFileList{$path}}) {
			if (!defined($srcFileList{$path}->{$fname})) {
Nigel Kukard's avatar
Nigel Kukard committed
690
				printLog(LOG_DEBUG,"File '[$source]/($path)/$fname' removed\n");
Nigel Kukard's avatar
Nigel Kukard committed
691
692
693
694
695
696
697
698
699
				$doBackup{$path} |= ST_FILE_CHANGED;
			}
		}

		# Create backup dir
		if (($doBackup{$path} & ST_DIR_NEW) == ST_DIR_NEW && ! -d "$dest/$path") {
			mkpath("$dest/$path");
		}

Nigel Kukard's avatar
Nigel Kukard committed
700
701
702
703
704
705
706
707
		# NK:
		# Before we do anything, we copy our previous attributes.
		# If we do not write an archive below, we still have our stuff.
		# If there is something special, we still have it. Best idea? right?
		foreach my $item (keys %{$origPathAttribs{$path}}) {
			$newPathAttribs{$path}->{$item} = $origPathAttribs{$path}->{$item};
		}

Nigel Kukard's avatar
Nigel Kukard committed
708
709
		# Check if we need to backup this dir
		if (($doBackup{$path} & ST_FILE_CHANGED) == ST_FILE_CHANGED) {
Nigel Kukard's avatar
Nigel Kukard committed
710
			printLog(LOG_INFO,"B: Path '[$source]/$path' backing up\n");
Nigel Kukard's avatar
Nigel Kukard committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763

			# If we not backing up a system dir, we create a manifest and backup the files
			if (($doBackup{$path} & ST_DIR_SYS) != ST_DIR_SYS) {
				# Did file contents change?
				my $changedFiles = 0;
				my $changedAttrs = 0;
				my @newFiles = ();
				my @manifestList;

				# Take a look quick...
				foreach my $item (sort keys %{$curFileList}) {
					# Lets see whats happened...
					if (($curFileList->{$item}->{'_state'} & ST_FILE_NEW) == ST_FILE_NEW) {
						push(@newFiles,$item);
					}
					if (($curFileList->{$item}->{'_state'} & ST_FILE_CHANGED) == ST_FILE_CHANGED) {
						$changedFiles = 1;
					}
					if (($curFileList->{$item}->{'_state'} & ST_FILE_ATTR_CHANGED) == ST_FILE_ATTR_CHANGED) {
						$changedAttrs = 1;
					}
				}

				# If we don't have a sequence, this is a new backup?
				if (!defined($newPathAttribs{$path}->{'sequence'} = $origPathAttribs{$path}->{'sequence'})) {
					$newPathAttribs{$path}->{'sequence'} = 0;
					@manifestList = keys %{$curFileList};
				} else {
					# If this is new files, then just inc the counter
					if (@newFiles > 0 && !$changedFiles && !$changedAttrs) {
						$newPathAttribs{$path}->{'sequence'}++;
						@manifestList = @newFiles;
					# If files changed we blow everything away
					} else {
						$newPathAttribs{$path}->{'sequence'} = 0;
						# Remove old files	
						removeBackups(
								"$dest/$path",
								$origPathAttribs{$path}->{'format'},
								$origPathAttribs{$path}->{'compression'},
								$origPathAttribs{$path}->{'sequence'}
						);
						@manifestList = keys %{$curFileList};
					}
				}


				# Get current sequence
				my $seq = $newPathAttribs{$path}->{'sequence'};

				# Setup tar args
				my @tarArgs = ();
				my $tarExt;
764
				if ($config{'compress'} eq "xz") {
Nigel Kukard's avatar
Nigel Kukard committed
765
766
					push(@tarArgs,"--xz");
					$tarExt = ".xz";
767
				} elsif ($config{'compress'} eq "bzip2") {
Nigel Kukard's avatar
Nigel Kukard committed
768
769
					push(@tarArgs,"--bzip2");
					$tarExt = ".bz2";
770
				} elsif ($config{'compress'} eq "gzip") {
Nigel Kukard's avatar
Nigel Kukard committed
771
772
					push(@tarArgs,"--gzip");
					$tarExt = ".gz";
773
				} elsif ($config{'compress'} eq "none") {
Nigel Kukard's avatar
Nigel Kukard committed
774
775
776
777
778
					$tarExt = "";
				}

				# Save format and compression
				$newPathAttribs{$path}->{'format'} = "tar";
779
				$newPathAttribs{$path}->{'compression'} = $config{'compress'};
Nigel Kukard's avatar
Nigel Kukard committed
780

781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
				# Sort out manifest format
				my $manifestDelim;
				# Are we overriding the manifest format?
				if (defined($config{'manifest-format'})) {
					$newPathAttribs{$path}->{'manifest.format'} = $config{'manifest-format'};
				} else {
					# If not choose best
					if (defined($origPathAttribs{$path}->{'manifest.format'})) {
						$newPathAttribs{$path}->{'manifest.format'} = $origPathAttribs{$path}->{'manifest.format'};
					} else {
						# Tar pre-1.22 is buggered with \0 manifest files
						if ($tarVer > 122) {
							$newPathAttribs{$path}->{'manifest.format'} = "null";
						} else {
							$newPathAttribs{$path}->{'manifest.format'} = "newline";
						}	
					}
				}

				# Setup manifest delim & tar options
				if ($newPathAttribs{$path}->{'manifest.format'} eq "null") {
					push(@tarArgs,"--null");
					push(@tarArgs,"--files-from", "$dest/$path/dbackup$seq.manifest");
					push(@tarArgs,"--no-unquote");
					$manifestDelim = "\0";
				} elsif ($newPathAttribs{$path}->{'manifest.format'} eq "newline") {
					push(@tarArgs,"--files-from", "$dest/$path/dbackup$seq.manifest");
					$manifestDelim = "\n";
				} else {
					printLog(LOG_ERROR,"Invalid manifest.format '".$newPathAttribs{$path}->{'manifest.format'}."'\n");
					exit 1;
				}

				# File list to backup
				open(MANIFEST,"> $dest/$path/dbackup$seq.manifest")
Nigel Kukard's avatar
Nigel Kukard committed
816
						or die "Failed to open '[$dest]/($path)/dbackup$seq.manifest': $!";
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
				foreach my $item (@manifestList) {
					# Sanity check to see if this filename is going to work
					if ($manifestDelim eq "\n" && $item =~ /[\n"'\\]/) {
						printLog(LOG_ERROR,"ERROR: Your version of tar cannot backup => path:'$path', file '$item'\n");
						next;
					}
					# If this is not the top dir, use /
					if ($path ne "") {
						print(MANIFEST "$path/$item$manifestDelim");
					# If it is, don't use /
					} else {
						print(MANIFEST "$item$manifestDelim");
					}
				}
				close(MANIFEST);

833
834
835
836
837
838
839
840
841
842
843
844
				# tar specifics...
				if ($newPathAttribs{$path}->{'format'} eq "tar") {
					# Exclude paths for tar-ignore-failed-read
					foreach my $item (@{$config{'tar-ignore-failed-read'}}) {
						# Check...
						if ("/$path" eq $item) {
							printLog(LOG_NOTICE,"B: Path '[$source]/$path' ignore-failed-read passed to tar\n");
							push(@tarArgs,"--ignore-failed-read",$path);
						}
					}
				}

Nigel Kukard's avatar
Nigel Kukard committed
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
				# Change dir and start backup
				system(
					"tar", 
					"--create",
					"--verbose",
					# Output file
					"--file", "$dest/$path/dbackup$seq.tar$tarExt",
					# cd into here first...
					"--directory", "$source",
					# Do not recurse
					"--no-recursion",
					# Output to this file
					"--index-file", "$dest/$path/dbackup$seq.index",
					# Incremental options
#					"--listed-incremental", "$dest/$path/dbackup.snar",
#					"--no-check-device",
					@tarArgs
				);
				if ($? == -1) {
Nigel Kukard's avatar
Nigel Kukard committed
864
					printLog(LOG_ERROR,"Failed to execute: $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
865
866
					exit 1;
				} elsif ($? & 127) {
867
					printLog(LOG_ERROR,"Child died with signal %s\n",($? & 127));
Nigel Kukard's avatar
Nigel Kukard committed
868
869
870
871
					exit 1;
				} else {
					my $retcode = $? >> 8;
					# If tar died, lets die too
872
					if ($retcode >= 2) {
Nigel Kukard's avatar
Nigel Kukard committed
873
						printLog(LOG_ERROR,"tar died with error code $retcode\n");
Nigel Kukard's avatar
Nigel Kukard committed
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
						exit 1;
					}
				}
			# if (($doBackup{$path} & ST_DIR_SYS) != ST_DIR_SYS) {
			} else {
					# Remove old files	
					removeBackups(
							"$dest/$path",
							$origPathAttribs{$path}->{'format'},
							$origPathAttribs{$path}->{'compression'},
							$origPathAttribs{$path}->{'sequence'}
					);
			}
		} # if (($doBackup{$path} & ST_FILE_CHANGED) == ST_FILE_CHANGED) {


		# Check if we need to record directory changes...
		if (
					($doBackup{$path} & ST_FILE_CHANGED) == ST_FILE_CHANGED ||
					($doBackup{$path} & ST_DIR_CHANGED) == ST_DIR_CHANGED ||
					($doBackup{$path} & ST_DIR_NEW) == ST_DIR_NEW
		) {
			# If we have a revision, bump it
			if (defined($newPathAttribs{$path}->{'revision'} = $origPathAttribs{$path}->{'revision'})) {
				$newPathAttribs{$path}->{'revision'} = $origPathAttribs{$path}->{'revision'} + 1;
			} else {
				$newPathAttribs{$path}->{'revision'} = 0;
			}

Nigel Kukard's avatar
Nigel Kukard committed
903
904
905
906
			# Set this as the dbackup that created this file
			$newPathAttribs{$path}->{'dbackup.version'} = $VERSION;

			printLog(LOG_DEBUG,"B: Writing state '[$source]/($path)' - revision ".$newPathAttribs{$path}->{'revision'}."\n");
Nigel Kukard's avatar
Nigel Kukard committed
907
908
909

			# Write out state, we do this AFTER we have backed up, so if we stopped, we can just  continue
			my $gz = gzopen("$dest/$path/.dbackup-state","wb")
Nigel Kukard's avatar
Nigel Kukard committed
910
					or die "Failed to open '[$dest]/($path)/.dbackup-state': $!";
Nigel Kukard's avatar
Nigel Kukard committed
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
			# Loop with attributes
			foreach my $item (keys %{$newPathAttribs{$path}}) {
				$gz->gzwrite(join("\0",
						"a",
						$item,
						$newPathAttribs{$path}->{$item}	
					)."\n"
				);
			}
			# Loop with directory list
			foreach my $item (sort keys %{$curDirList}) {
				my $ename = encode_base64($item);
				$ename =~ s/\n//g;
				# Save state of source files
				$gz->gzwrite(join("\0",
						"d",
						$ename,
						$curDirList->{$item}->{'ctime'},
						$curDirList->{$item}->{'atime'},
						$curDirList->{$item}->{'mtime'},
						$curDirList->{$item}->{'uid'},
						$curDirList->{$item}->{'gid'},
						$curDirList->{$item}->{'mode'}
					)."\n"
				);
			}
			# Loop with file list
			foreach my $item (sort keys %{$curFileList}) {
				my $ename = encode_base64($item);
				$ename =~ s/\n//g;
				# Save state of source files
				$gz->gzwrite(join("\0",
						"f",
						$ename,
						$curFileList->{$item}->{'size'},
						$curFileList->{$item}->{'ctime'},
						$curFileList->{$item}->{'atime'},
						$curFileList->{$item}->{'mtime'},
						$curFileList->{$item}->{'uid'},
						$curFileList->{$item}->{'gid'},
						$curFileList->{$item}->{'mode'}
					)."\n"
				);
			}
			# Finally close
			$gz->gzclose();
		}

		# State clear
		delete($origFileList{$path});
	}

Nigel Kukard's avatar
Nigel Kukard committed
963
964
	printLog(LOG_NOTICE,"BACKUP START: $source => $dest\n");
	printLog(LOG_INFO,"Compression: ".$config{'compress'}."\n");
965

Nigel Kukard's avatar
Nigel Kukard committed
966
	# Check if we excluding system files
967
	if ($config{'exclude-system'}) {
Nigel Kukard's avatar
Nigel Kukard committed
968
969
		printLog(LOG_NOTICE,"Exclude System Base: ".join(", ",@{$config{'system-base'}})."\n");
		printLog(LOG_NOTICE,"Exclude System Dirs: ".join(", ",@defaultSystemExcl,@{$config{'system-dir'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
970
		# If we excluding data too...
971
		if ($config{'exclude-data'}) {
Nigel Kukard's avatar
Nigel Kukard committed
972
			printLog(LOG_NOTICE,"Exclude Data Dirs: ".join(", ",@defaultDataExcl,@{$config{'data-dir'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
973
974
		}
	}
975
	printLog(LOG_NOTICE,"Exclude Paths: ".join(", ",@{$config{'exclude-path'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
976
	printLog(LOG_NOTICE,"Exclude Files: ".join(", ",@{$config{'exclude-file'}})."\n");
Nigel Kukard's avatar
Nigel Kukard committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991

	# We need an entry for our main dir before we start
	$doBackup{""} = 0;

	# This basically does our backup for us...
	find (
		{ 
			preprocess => \&backup_preprocess,
			wanted => \&backup_process,
			postprocess => \&backup_postprocess
		},
		$source
	);


Nigel Kukard's avatar
Nigel Kukard committed
992
	printLog(LOG_INFO,"Processing stale directories...\n");
Nigel Kukard's avatar
Nigel Kukard committed
993
994
995
996
997
998
999
1000
1001
1002
1003
	my @rmlist;
	# Total item by item
	find (
		{ 
			wanted => sub { },
			# We just need post processing ...
			postprocess => sub {
				# Strip first part of the path
				(my $path = $File::Find::dir) =~ s#^$dest/?##;
				# Does this dir exist on the backup, but not on the fileserver?
				if (!defined($srcFileList{$path})) {
Nigel Kukard's avatar
Nigel Kukard committed
1004
					push(@rmlist,$path);
Nigel Kukard's avatar
Nigel Kukard committed
1005
1006
1007
1008
1009
1010
				}
			},
		},
		$dest
	);
	foreach my $rmitem ( @rmlist ) {
Nigel Kukard's avatar
Nigel Kukard committed
1011
		printLog(LOG_DEBUG,"Remove path '[$dest]/($rmitem)'\n");
Nigel Kukard's avatar
Nigel Kukard committed
1012
   		rmtree("$dest/$rmitem");
Nigel Kukard's avatar
Nigel Kukard committed
1013
1014
	}

Nigel Kukard's avatar
Nigel Kukard committed
1015
	printLog(LOG_NOTICE,"BACKUP END\n");
Nigel Kukard's avatar
Nigel Kukard committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
}


# Do backup
if (defined($optctl{'backup'})) {
	backup($sourceDir,$destDir);

} elsif (defined($optctl{'restore'})) {
	restore($sourceDir,$destDir);

} else {
	print(STDERR "ERROR: No command given\n\n");
	displayHelp();
	exit 1;
}


# Restore function
sub restore
{
	our ($source,$dest) = @_;

	# State infor for current dir
#	our %doBackup;
#	our %srcFileList;
#	our %srcDirList;
	our %origFileList;
	our %origDirList;
	our %origPathAttribs;


	# Preprocess dir
	sub restore_preprocess {
		my @list = @_;

		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Check if we have all our source files
		if ( ! -f "$source/$path/.dbackup-state" ) {
Nigel Kukard's avatar
Nigel Kukard committed
1056
			printLog(LOG_WARNING,"S: Path '[$source]/($path)' is MISSING .dbackup-state\n");
Nigel Kukard's avatar
Nigel Kukard committed
1057
1058
1059
1060
1061
1062
1063
1064
			return @list;
		}

		# Load state file
		loadStateFile("$source/$path/.dbackup-state",$path,\%origFileList,\%origDirList,\%origPathAttribs);

		# Check we have at least the version attribute
		if (!defined($origPathAttribs{$path}) || !defined($origPathAttribs{$path}->{'dbackup.version'})) {
Nigel Kukard's avatar
Nigel Kukard committed
1065
			printLog(LOG_ERROR, "No dbackup version information found in '[$source]/($path)/.dbackup-state', IGNORING\n");
Nigel Kukard's avatar
Nigel Kukard committed
1066
1067
1068
1069
1070
1071
1072
1073
			delete($origDirList{$path});
			delete($origFileList{$path});
			return @list;
		}

		# During our check, we need to create the dir, we may not have a backup file
		# so we do it here.
		if ( ! -d "$dest/$path") {
Nigel Kukard's avatar
Nigel Kukard committed
1074
			printLog(LOG_INFO,"R: Path '[$dest]/($path)' creating directory\n");
Nigel Kukard's avatar
Nigel Kukard committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
			mkpath("$dest/$path");
		}

		# The lack of a sequence number probably means we didn't output any tar files during backup
		if (!defined($origPathAttribs{$path}->{'sequence'})) {
			return @list;
		}

		# Loop through backup sequences
		for (my $seq = 0; $seq <= $origPathAttribs{$path}->{'sequence'}; $seq++) {
Nigel Kukard's avatar
Nigel Kukard committed
1085
			printLog(LOG_DEBUG,"R: Path '[$dest]/($path)' restoring data ".($seq+1)." of ".
Nigel Kukard's avatar
Nigel Kukard committed
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
					($origPathAttribs{$path}->{'sequence'}+1)."\n");

			# Args for tar
			my @tarArgs = ();

			my $tarExt;
			if ($origPathAttribs{$path}->{'compression'} eq "xz") {
				push(@tarArgs,"--xz");
				$tarExt = ".xz";
			} elsif ($origPathAttribs{$path}->{'compression'} eq "bzip2") {
				push(@tarArgs,"--bzip2");
				$tarExt = ".bz2";
			} elsif ($origPathAttribs{$path}->{'compression'} eq "gzip") {
				push(@tarArgs,"--gzip");
				$tarExt = ".gz";
			} elsif ($origPathAttribs{$path}->{'compression'} eq "none") {
				$tarExt = "";
			}

			# Check what type of backup we did
			if ( ! -f "$source/$path/dbackup$seq.tar$tarExt" ) {
				# If we have any other part of the backup, show a message
				if (
							( -f "$source/$path/dbackup$seq.index" || 
							-f "$source/$path/dbackup$seq.manifest" ||
							-f "$source/$path/dbackup$seq.snar" ) && $seq > 0
				) {
Nigel Kukard's avatar
Nigel Kukard committed
1113
					printLog(LOG_WARNING,"Backup file '[$source]/($path)/dbackup$seq.tar$tarExt' not found, IGNORING\n");
Nigel Kukard's avatar
Nigel Kukard committed
1114
1115
1116
1117
1118
1119
1120
				}

				return @list;
			}

			# Check we have files we need/created
			if ( ! -f "$source/$path/dbackup$seq.index" ) {
Nigel Kukard's avatar
Nigel Kukard committed
1121
				printLog(LOG_WARNING,"Manifest file '[$source]/($path)/dbackup$seq.index' not found\n");
Nigel Kukard's avatar
Nigel Kukard committed
1122
1123
1124
				return @list;
			}
			if ( ! -f "$source/$path/dbackup$seq.manifest" ) {
Nigel Kukard's avatar
Nigel Kukard committed
1125
				printLog(LOG_WARNING,"Manifest file '[$source]/($path)/dbackup$seq.manifest' not found\n");
Nigel Kukard's avatar
Nigel Kukard committed
1126
1127
1128
				return @list;
			}

Nigel Kukard's avatar
Nigel Kukard committed
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
			# Check if manifest.format is undefined, if it is, use the default
			if (!defined($origPathAttribs{$path}->{'manifest.format'})) {
				# Check if we have a commandline override
				if (defined($optctl{'manifest-format'})) {
					$origPathAttribs{$path}->{'manifest.format'} = $optctl{'manifest-format'};
				} else {
					# NK:
					# Default to null
					# This saves us from having to regenerate manifest.format attrs and backups for older
					# versions of dbackup.
					$origPathAttribs{$path}->{'manifest.format'} = "null";
				}
			}

1143
1144
1145
1146
1147
1148
1149
1150
			# Setup manifest delim & tar options
			if ($origPathAttribs{$path}->{'manifest.format'} eq "null") {
				push(@tarArgs,"--null");
				push(@tarArgs,"--files-from", "$source/$path/dbackup$seq.manifest");
				push(@tarArgs,"--no-unquote");
			} elsif ($origPathAttribs{$path}->{'manifest.format'} eq "newline") {
				push(@tarArgs,"--files-from", "$source/$path/dbackup$seq.manifest");
			} else {
Nigel Kukard's avatar
Nigel Kukard committed
1151
1152
				printLog(LOG_ERROR,"Invalid manifest.format '".$origPathAttribs{$path}->{'manifest.format'}.
						"' for '[$source]/($path)', try setting the default with --manifest-format=\n");
1153
1154
1155
1156
1157
1158
1159
1160
1161
				exit 1;
			}

			# Sanity check
			if ($tarVer < 122 && $origPathAttribs{$path}->{'manifest.format'} eq "null") {
				printLog(LOG_ERROR,"Your version of tar does NOT support manifest.format of 'null'\n");
				exit 1;
			}

Nigel Kukard's avatar
Nigel Kukard committed
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
			# Other tar options
			if (defined($optctl{'tar-keep-newer'})) {
				push(@tarArgs,"--keep-newer-files");
			}
			if (defined($optctl{'tar-keep-old-files'})) {
				push(@tarArgs,"--keep-old-files");
			}

			# Change dir and start backup
			system(
				"tar", 
				"--extract",
				# Output file
				"--file", "$source/$path/dbackup$seq.tar$tarExt",
				# cd into here first...
				"--directory", "$dest",
				# Do not recurse
				"--no-recursion",
				# Incremental options
#			"--incremental",
				@tarArgs
			);
			if ($? == -1) {
Nigel Kukard's avatar
Nigel Kukard committed
1185
				printLog(LOG_ERROR,"Failed to execute: $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1186
1187
				exit 1;
			} elsif ($? & 127) {
1188
				printLog(LOG_ERROR,"Child died with signal %s\n",($? & 127));
Nigel Kukard's avatar
Nigel Kukard committed
1189
1190
1191
1192
				exit 1;
			} else {
				my $retcode = $? >> 8;
				# If tar died, lets die too
1193
				if ($retcode >= 2) {
Nigel Kukard's avatar
Nigel Kukard committed
1194
					printLog(LOG_ERROR,"tar died with error code $retcode\n");
Nigel Kukard's avatar
Nigel Kukard committed
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
					exit 1;
				}
			}
		}

		return @list;
	}

	# Process files
	sub restore_process {
		my $name = $File::Find::name;
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

		# Store current filename
		my $item = $_;

#		print(STDERR "PROCESS: Path = $path, Name = $name, Item = $item)\n");
	}


	# Time to do stuff
	sub restore_postprocess {
		# Strip first part of the path
		(my $path = $File::Find::dir) =~ s#^$source/?##;

Nigel Kukard's avatar
Nigel Kukard committed
1221
		printLog(LOG_DEBUG,"R: Path '[$dest]/($path)' restoring meta-data\n");
Nigel Kukard's avatar
Nigel Kukard committed
1222
1223
1224
1225
1226
1227
1228
1229
1230

		# Loop with directories in this path
		foreach my $dname (keys %{$origDirList{$path}}) {
			# Set dir
			my $dir = $origDirList{$path}->{$dname};

			# Full dirname
			my $fdirname = "$dest/$path/$dname";

Nigel Kukard's avatar
Nigel Kukard committed
1231
1232
1233
1234
1235
1236
			# Could be a dir with no contents of one which was ignored, in which case we must create it
			if (! -d $fdirname) {
				printLog(LOG_INFO,"R: Path '[$dest]/($path)/$dname' creating missing directory\n");
				mkpath($fdirname);
			}

Nigel Kukard's avatar
Nigel Kukard committed
1237
1238
			# Restore attribs
			if (!chown($dir->{'uid'},$dir->{'gid'},$fdirname)) {
Nigel Kukard's avatar
Nigel Kukard committed
1239
				printLog(LOG_ERROR,"Failed to chown(".$dir->{'uid'}.",".$dir->{'gid'}.") '$fdirname': $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1240
1241
			}
			if (!chmod($dir->{'mode'},$fdirname)) {
Nigel Kukard's avatar
Nigel Kukard committed
1242
				printLog(LOG_ERROR,"Failed to chmod(".$dir->{'mode'}.") '$fdirname': $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1243
1244
			}
			if (!utime($dir->{'atime'},$dir->{'mtime'},$fdirname)) {
Nigel Kukard's avatar
Nigel Kukard committed
1245
				printLog(LOG_ERROR,"Failed to utime(".$dir->{'atime'}.",".$dir->{'mtime'}.") '$fdirname': $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
			}
		}

		# Loop with files in this path
		foreach my $fname (keys %{$origFileList{$path}}) {
			# Set dir
			my $file = $origFileList{$path}->{$fname};

			# Full dirname
			my $ffilename = "$dest/$path/$fname";

1257
1258
1259
			# Restore for links and files
			if (!lchown($file->{'uid'},$file->{'gid'},$ffilename)) {
				printLog(LOG_ERROR,"Failed to lchown(".$file->{'uid'}.",".$file->{'gid'}.") '$ffilename': $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1260
			}
1261
1262
1263
1264
1265

			# Ignore links for the rest...
			next if (S_ISLNK($file->{'mode'}));

			# Restore mode & utime only for files
Nigel Kukard's avatar
Nigel Kukard committed
1266
			if (!chmod($file->{'mode'},$ffilename)) {
Nigel Kukard's avatar
Nigel Kukard committed
1267
				printLog(LOG_ERROR,"Failed to chmod(".$file->{'mode'}.") '$ffilename': $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1268
1269
			}
			if (!utime($file->{'atime'},$file->{'mtime'},$ffilename)) {
Nigel Kukard's avatar
Nigel Kukard committed
1270
				printLog(LOG_ERROR,"Failed to utime(".$file->{'atime'}.",".$file->{'mtime'}.") '$ffilename': $!\n");
Nigel Kukard's avatar
Nigel Kukard committed
1271
1272
1273
1274
			}
		}
	}

Nigel Kukard's avatar
Nigel Kukard committed
1275
	printLog(LOG_NOTICE,"RESTORE START: $source => $dest\n");
Nigel Kukard's avatar
Nigel Kukard committed
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286

	# This basically does our backup for us...
	find (
		{ 
			preprocess => \&restore_preprocess,
			wanted => \&restore_process,
			postprocess => \&restore_postprocess
		},
		$source
	);

Nigel Kukard's avatar
Nigel Kukard committed
1287
	printLog(LOG_NOTICE,"RESTORE END\n");
Nigel Kukard's avatar
Nigel Kukard committed
1288
1289
1290
1291
1292
}


# Display log line
sub printLog {
Nigel Kukard's avatar
Nigel Kukard committed
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
	my ($level,$msg,@args) = @_;


	# Work out level txt all nicely
	my $levelTxt = "UNKNOWN";
	if ($level == LOG_DEBUG) {
		$levelTxt = "DEBUG";
	} elsif ($level == LOG_INFO) {
		$levelTxt = "INFO";
	} elsif ($level == LOG_NOTICE) {
		$levelTxt = "NOTICE";
	} elsif ($level == LOG_WARNING) {
		$levelTxt = "WARNING";
1306
1307
	} elsif ($level == LOG_ERROR) {
		$levelTxt = "ERROR";
Nigel Kukard's avatar
Nigel Kukard committed
1308
	}
Nigel Kukard's avatar
Nigel Kukard committed
1309

Nigel Kukard's avatar
Nigel Kukard committed
1310
	# Check log level
Nigel Kukard's avatar
Nigel Kukard committed
1311
	if ($level <= $config{'log-level'}) {
Nigel Kukard's avatar
Nigel Kukard committed
1312
1313
		printf(STDERR "%s/$levelTxt: %s", strftime('%F %T',localtime()), $msg, @args);
	}
Nigel Kukard's avatar
Nigel Kukard committed
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
}



# Display usage
sub displayHelp {
	# Build some strings we need
	my $systemDirStr = join (", ",@defaultSystemExcl);
	my $dataDirStr = join (", ",@defaultDataExcl);

	print(STDERR<<EOF);
Usage: $0 [args] <src> <dst>

    General Options:
      --help                             What you seeing now.
Nigel Kukard's avatar
Nigel Kukard committed
1329
      --config=file                      Config file to use.
Nigel Kukard's avatar
Nigel Kukard committed
1330
1331
      --log-level                        1 = debug, 2 = info, 3 = notice
                                         4 = warning, 5 = debug
1332
      --tar                              Path to tar binary.
Nigel Kukard's avatar
Nigel Kukard committed
1333
1334
1335

    Backing Options:
      --backup|-b                        Backup src to dst.
Nigel Kukard's avatar
Nigel Kukard committed
1336
      --backup-upgrade                   Upgrade backup to new dbackup ver.
Nigel Kukard's avatar
Nigel Kukard committed
1337
1338
1339
      --compress=<xz|bz2|gz|none>        Compression method to use defaults
                                         to using xz, or bzip2 if xz unavail.

1340
1341
1342
1343
1344
      --exclude-data                     Exclude all data dirs listed below.
      --exclude-system                   Exclude system dirs listed below.

      --exclude-path=pcre                PCRE to exclude paths from backup.
      --exclude-file=pcre                PCRE to exclude files from backup.
1345
1346
      
      --exclude-fs-type=fstype           Filesystem type to exclude.
1347
1348
1349
1350
1351

      --data-dir=dir                     Add an additional data directory.
      --system-dir=dir                   Add an additional systemd directory.
      --system-base=path                 Add a system base. This defaults to /
                                         and this option will override that.
1352

1353
1354
1355
1356
      --tar-ignore-failed-read=path      This is passed to tar only. It will
                                         not cause errors of files that cannot
                                         be read for the path matched.

Nigel Kukard's avatar
Nigel Kukard committed
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
    Restore Options:
      --restore|-r                       Restore src to dst.
      --tar-keep-newer                   Do not overwrite newer files.
      --tar-keep-old-files               Don't replace existing files.


Builtins:
---------
    system-dirs:
      $systemDirStr

    data-dirs:
      $dataDirStr
EOF
} 


#
# LIBRARY
#

sub loadStateFile {
		my ($statefile,$key,$fileList,$dirList,$pathAttribs) = @_;


		# Read in backup state file, we do it here because we may not have a backup file
		# to restore
		my $gz = gzopen($statefile,"rb") 
				or die "FATAL ERROR: Failed to open '$statefile': $!";
		# Read in file list
		my $line;
		while ($gz->gzreadline($line) > 0) {
			chomp($line);
			# Pull out array of items
			my @aline = split(/\0/,$line);
			my $type = shift(@aline);
			# Check if its defined
			if (defined($type)) {
				# If its a file...
				if ($type eq "f") {
					my ($ename,$size,$ctime,$atime,$mtime,$uid,$gid,$mode) = @aline;
					my $name = decode_base64($ename);
					# Setup our hash
					$fileList->{$key}->{$name}->{'size'} = $size;
					$fileList->{$key}->{$name}->{'ctime'} = $ctime;
					$fileList->{$key}->{$name}->{'atime'} = $atime;
					$fileList->{$key}->{$name}->{'mtime'} = $mtime;
					$fileList->{$key}->{$name}->{'uid'} = $uid;
					$fileList->{$key}->{$name}->{'gid'} = $gid;
					$fileList->{$key}->{$name}->{'mode'} = $mode;
				# If its a dir
				} elsif ($type eq "d") {
					my ($ename,$ctime,$atime,$mtime,$uid,$gid,$mode) = @aline;
					my $name = decode_base64($ename);
					# Setup our hash
					$dirList->{$key}->{$name}->{'ctime'} = $ctime;
					$dirList->{$key}->{$name}->{'atime'} = $atime;
					$dirList->{$key}->{$name}->{'mtime'} = $mtime;
					$dirList->{$key}->{$name}->{'uid'} = $uid;
					$dirList->{$key}->{$name}->{'gid'} = $gid;
					$dirList->{$key}->{$name}->{'mode'} = $mode;
				# Attribute
				} elsif ($type eq "a") {
					my ($name,$value) = @aline;
					$pathAttribs->{$key}->{$name} = $value;
				# Unknown
				} else {
					print(STDERR "ERROR: Invalid type '$type' in '$statefile'\n");
					exit 1;
				}
			}
		}
		# Close gzip file
		$gz->gzclose();
}


sub removeBackups
{
	my ($path,$format,$compression,$seqs) = @_;


	# Loop through backup sequences
	for (my $i = 0; $i <= $seqs; $i++) {

		my $tarExt;
		if ($compression eq "xz") {
			$tarExt = ".xz";
		} elsif ($compression eq "bzip2") {
			$tarExt = ".bz2";
		} elsif ($compression eq "gzip") {
			$tarExt = ".gz";
		} elsif ($compression eq "none") {
			$tarExt = "";
		}

		# Unlink backup files
		if (-f "$path/dbackup$i.tar$tarExt") {
			unlink("$path/dbackup$i.tar$tarExt")
					or die "ERROR: Failed to remove file '$path/dbackup$i.tar$tarExt': $!";
		}
		# Unlink manifest
		if (-f "$path/dbackup$i.manifest") {
			unlink("$path/dbackup$i.manifest")
					or die "ERROR: Failed to remove file '$path/dbackup$i.manifest': $!";
		}
		# Unlink index
		if (-f "$path/dbackup$i.index") {
			unlink("$path/dbackup$i.index")
					or die "ERROR: Failed to remove file '$path/dbackup$i.index': $!";
		}
		# Unlink snar
		if (-f "$path/dbackup$i.snar") {
			unlink("$path/dbackup$i.snar")
					or die "ERROR: Failed to remove file '$path/dbackup$i.snar': $!";
		}

	}
}

1477
1478
1479
1480
1481
1482
1483
sub toArray
{
	my $param = shift;

	if (ref $param eq "ARRAY") {
		return $param;
	} else {
1484
		return [ split(/\n/,$param) ];
1485
1486
	}
}
Nigel Kukard's avatar
Nigel Kukard committed
1487

1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
sub getTarVer
{
	my $tar = shift;

	open(TAR, $config{'tar'} . " --version |")
		or die "FAILED to execute '".$config{'tar'}."': $!";
	if (!($tarVer = <TAR>)) {
		print(STDERR "ERROR: Failed to read tar version\n");
		exit 1;
	}
	($tarVer) = ($tarVer =~ /([0-9]+\.[0-9]+)/);
	if (!defined($tarVer) || $tarVer eq "") {
		print(STDERR "ERROR: Failed to parse tar version\n");
		exit 1;
	}
	$tarVer =~ s/\.//g;
	close(TAR);
	if ($tarVer < 100) {
		print(STDERR "ERROR: Failed to read tar version or your version is simply too old\n");
		exit 1;
	}
Nigel Kukard's avatar
Nigel Kukard committed
1509
1510

	return $tarVer;
1511
1512
}

Nigel Kukard's avatar
Nigel Kukard committed
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
sub getNumericVer
{
	my $a = shift;

	# 000 000 000
	my @a = split(/\./,$a);

	# Quick fix for devel versions
	$a[2] = 0 if ($a[2] eq "x");

	return ( ($a[0]*1000000) + ($a[1]*1000) + $a[2] );
}

Nigel Kukard's avatar
Nigel Kukard committed
1526
# vim: ts=4