- fixed configure.pl and makeDist.
[BackupPC.git] / lib / BackupPC / Storage / Text.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Storage::Text package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Storage::Text class that implements
8 #   BackupPC's persistent state storage (config, host info, backup
9 #   and restore info) using text files.
10 #
11 # AUTHOR
12 #   Craig Barratt  <cbarratt@users.sourceforge.net>
13 #
14 # COPYRIGHT
15 #   Copyright (C) 2004  Craig Barratt
16 #
17 #   This program is free software; you can redistribute it and/or modify
18 #   it under the terms of the GNU General Public License as published by
19 #   the Free Software Foundation; either version 2 of the License, or
20 #   (at your option) any later version.
21 #
22 #   This program is distributed in the hope that it will be useful,
23 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
24 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 #   GNU General Public License for more details.
26 #
27 #   You should have received a copy of the GNU General Public License
28 #   along with this program; if not, write to the Free Software
29 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30 #
31 #========================================================================
32 #
33 # Version 3.0.0alpha, released 23 Jan 2006.
34 #
35 # See http://backuppc.sourceforge.net.
36 #
37 #========================================================================
38
39 package BackupPC::Storage::Text;
40
41 use strict;
42 use vars qw(%Conf);
43 use Data::Dumper;
44 use File::Path;
45 use Fcntl qw/:flock/;
46
47 sub new
48 {
49     my $class = shift;
50     my($flds, $paths) = @_;
51
52     my $s = bless {
53         %$flds,
54         %$paths,
55     }, $class;
56     return $s;
57 }
58
59 sub setPaths
60 {
61     my $class = shift;
62     my($paths) = @_;
63
64     foreach my $v ( keys(%$paths) ) {
65         $class->{$v} = $paths->{$v};
66     }
67 }
68
69 sub BackupInfoRead
70 {
71     my($s, $host) = @_;
72     local(*BK_INFO, *LOCK);
73     my(@Backups);
74
75     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{TopDir}/pc/$host/LOCK");
76     if ( open(BK_INFO, "$s->{TopDir}/pc/$host/backups") ) {
77         binmode(BK_INFO);
78         while ( <BK_INFO> ) {
79             s/[\n\r]+//;
80             next if ( !/^(\d+\t(incr|full|partial).*)/ );
81             $_ = $1;
82             @{$Backups[@Backups]}{@{$s->{BackupFields}}} = split(/\t/);
83         }
84         close(BK_INFO);
85     }
86     close(LOCK);
87     return @Backups;
88 }
89
90 sub BackupInfoWrite
91 {
92     my($s, $host, @Backups) = @_;
93     my($i, $contents, $fileOk);
94
95     #
96     # Generate the file contents
97     #
98     for ( $i = 0 ; $i < @Backups ; $i++ ) {
99         my %b = %{$Backups[$i]};
100         $contents .= join("\t", @b{@{$s->{BackupFields}}}) . "\n";
101     }
102     
103     #
104     # Write the file
105     #
106     return $s->TextFileWrite("$s->{TopDir}/pc/$host/backups", $contents);
107 }
108
109 sub RestoreInfoRead
110 {
111     my($s, $host) = @_;
112     local(*RESTORE_INFO, *LOCK);
113     my(@Restores);
114
115     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{TopDir}/pc/$host/LOCK");
116     if ( open(RESTORE_INFO, "$s->{TopDir}/pc/$host/restores") ) {
117         binmode(RESTORE_INFO);
118         while ( <RESTORE_INFO> ) {
119             s/[\n\r]+//;
120             next if ( !/^(\d+.*)/ );
121             $_ = $1;
122             @{$Restores[@Restores]}{@{$s->{RestoreFields}}} = split(/\t/);
123         }
124         close(RESTORE_INFO);
125     }
126     close(LOCK);
127     return @Restores;
128 }
129
130 sub RestoreInfoWrite
131 {
132     my($s, $host, @Restores) = @_;
133     local(*RESTORE_INFO, *LOCK);
134     my($i, $contents, $fileOk);
135
136     #
137     # Generate the file contents
138     #
139     for ( $i = 0 ; $i < @Restores ; $i++ ) {
140         my %b = %{$Restores[$i]};
141         $contents .= join("\t", @b{@{$s->{RestoreFields}}}) . "\n";
142     }
143
144     #
145     # Write the file
146     #
147     return $s->TextFileWrite("$s->{TopDir}/pc/$host/restores", $contents);
148 }
149
150 sub ArchiveInfoRead
151 {
152     my($s, $host) = @_;
153     local(*ARCHIVE_INFO, *LOCK);
154     my(@Archives);
155
156     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{TopDir}/pc/$host/LOCK");
157     if ( open(ARCHIVE_INFO, "$s->{TopDir}/pc/$host/archives") ) {
158         binmode(ARCHIVE_INFO);
159         while ( <ARCHIVE_INFO> ) {
160             s/[\n\r]+//;
161             next if ( !/^(\d+.*)/ );
162             $_ = $1;
163             @{$Archives[@Archives]}{@{$s->{ArchiveFields}}} = split(/\t/);
164         }
165         close(ARCHIVE_INFO);
166     }
167     close(LOCK);
168     return @Archives;
169 }
170
171 sub ArchiveInfoWrite
172 {
173     my($s, $host, @Archives) = @_;
174     local(*ARCHIVE_INFO, *LOCK);
175     my($i, $contents, $fileOk);
176
177     #
178     # Generate the file contents
179     #
180     for ( $i = 0 ; $i < @Archives ; $i++ ) {
181         my %b = %{$Archives[$i]};
182         $contents .= join("\t", @b{@{$s->{ArchiveFields}}}) . "\n";
183     }
184
185     #
186     # Write the file
187     #
188     return $s->TextFileWrite("$s->{TopDir}/pc/$host/archives", $contents);
189 }
190
191 #
192 # Write a text file as safely as possible.  We write to
193 # a new file, verify the file, and the rename the file.
194 # The previous version of the file is renamed with a
195 # .old extension.
196 #
197 sub TextFileWrite
198 {
199     my($s, $file, $contents) = @_;
200     local(*FD, *LOCK);
201     my($fileOk);
202
203     (my $dir = $file) =~ s{(.+)/(.+)}{$1};
204
205     mkpath($dir, 0, 0775) if ( !-d $dir );
206     if ( open(FD, ">", "$file.new") ) {
207         binmode(FD);
208         print FD $contents;
209         close(FD);
210         #
211         # verify the file
212         #
213         if ( open(FD, "<", "$file.new") ) {
214             binmode(FD);
215             if ( join("", <FD>) ne $contents ) {
216                 return "TextFileWrite: Failed to verify $file.new";
217             } else {
218                 $fileOk = 1;
219             }
220             close(FD);
221         }
222     }
223     if ( $fileOk ) {
224         my $lock;
225         
226         if ( open(LOCK, "$dir/LOCK") || open(LOCK, ">", "$dir/LOCK") ) {
227             $lock = 1;
228             flock(LOCK, LOCK_EX);
229         }
230         if ( -s "$file" ) {
231             unlink("$file.old")           if ( -f "$file.old" );
232             rename("$file", "$file.old")  if ( -f "$file" );
233         } else {
234             unlink("$file") if ( -f "$file" );
235         }
236         rename("$file.new", "$file") if ( -f "$file.new" );
237         close(LOCK) if ( $lock );
238     } else {
239         return "TextFileWrite: Failed to write $file.new";
240     }
241     return;
242 }
243
244 sub ConfigPath
245 {
246     my($s, $host) = @_;
247
248     return "$s->{ConfDir}/config.pl" if ( !defined($host) );
249     if ( $s->{useFHS} ) {
250         return "$s->{ConfDir}/host/$host.pl";
251     } else {
252         return "$s->{ConfDir}/$host.pl"
253             if ( $host ne "config" && -f "$s->{ConfDir}/$host.pl" );
254         return "$s->{TopDir}/pc/$host/config.pl";
255     }
256 }
257
258 sub ConfigDataRead
259 {
260     my($s, $host) = @_;
261     my($ret, $mesg, $config, @configs);
262
263     #
264     # TODO: add lock
265     #
266     my $conf = {};
267     my $configPath = $s->ConfigPath($host);
268
269     push(@configs, $configPath) if ( -f $configPath );
270     foreach $config ( @configs ) {
271         %Conf = ();
272         if ( !defined($ret = do $config) && ($! || $@) ) {
273             $mesg = "Couldn't open $config: $!" if ( $! );
274             $mesg = "Couldn't execute $config: $@" if ( $@ );
275             $mesg =~ s/[\n\r]+//;
276             return ($mesg, $conf);
277         }
278         %$conf = ( %$conf, %Conf );
279     }
280     #
281     # Promote BackupFilesOnly and BackupFilesExclude to hashes
282     #
283     foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
284         next if ( !defined($conf->{$param}) || ref($conf->{$param}) eq "HASH" );
285         $conf->{$param} = [ $conf->{$param} ]
286                                 if ( ref($conf->{$param}) ne "ARRAY" );
287         $conf->{$param} = { "*" => $conf->{$param} };
288     }
289
290     return (undef, $conf);
291 }
292
293 sub ConfigDataWrite
294 {
295     my($s, $host, $newConf) = @_;
296
297     my $configPath = $s->ConfigPath($host);
298
299     my($err, $contents) = $s->ConfigFileMerge("$configPath", $newConf);
300     if ( defined($err) ) {
301         return $err;
302     } else {
303         #
304         # Write the file
305         #
306         return $s->TextFileWrite($configPath, $contents);
307     }
308 }
309
310 sub ConfigFileMerge
311 {
312     my($s, $inFile, $newConf) = @_;
313     local(*C);
314     my($contents, $out);
315     my $comment = 1;
316     my $skipVar = 0;
317     my $endLine = undef;
318     my $done = {};
319
320     if ( -f $inFile ) {
321         #
322         # Match existing settings in current config file
323         #
324         open(C, $inFile)
325             || return ("ConfigFileMerge: can't open/read $inFile", undef);
326         binmode(C);
327
328         while ( <C> ) {
329             if ( $comment && /^\s*#/ ) {
330                 $out .= $_;
331             } elsif ( /^\s*\$Conf\{([^}]*)\}\s*=/ ) {
332                 my $var = $1;
333                 if ( exists($newConf->{$var}) ) { 
334                     $contents .= $out;
335                     my $d = Data::Dumper->new([$newConf->{$var}], [*value]);
336                     $d->Indent(1);
337                     $d->Terse(1);
338                     my $value = $d->Dump;
339                     $value =~ s/(.*)\n/$1;\n/s;
340                     $contents .= "\$Conf{$var} = " . $value;
341                     $done->{$var} = 1;
342                 }
343                 $endLine = $1 if ( /^\s*\$Conf\{[^}]*} *= *<<(.*);/ );
344                 $endLine = $1 if ( /^\s*\$Conf\{[^}]*} *= *<<'(.*)';/ );
345                 $out = "";
346                 $skipVar = 1;
347             } elsif ( $skipVar ) {
348                 if ( !defined($endLine) && (/^\s*[\r\n]*$/ || /^\s*#/) ) {
349                     $skipVar = 0;
350                     $comment = 1;
351                     $out .= $_;
352                 }
353                 if ( defined($endLine) && /^\Q$endLine\E[\n\r]*$/ ) {
354                     $endLine = undef;
355                     $skipVar = 0;
356                     $comment = 1;
357                 }
358             } else {
359                 $out .= $_;
360             }
361         }
362         close(C);
363         $contents .= $out;
364     }
365
366     #
367     # Add new entries not matched in current config file
368     #
369     foreach my $var ( sort(keys(%$newConf)) ) {
370         next if ( $done->{$var} );
371         my $d = Data::Dumper->new([$newConf->{$var}], [*value]);
372         $d->Indent(1);
373         $d->Terse(1);
374         my $value = $d->Dump;
375         $value =~ s/(.*)\n/$1;\n/s;
376         $contents .= "\$Conf{$var} = " . $value;
377         $done->{$var} = 1;
378     }
379     return (undef, $contents);
380 }
381
382 #
383 # Return the mtime of the config file
384 #
385 sub ConfigMTime
386 {
387     my($s) = @_;
388     return (stat($s->ConfigPath()))[9];
389 }
390
391 #
392 # Returns information from the host file in $s->{ConfDir}/hosts.
393 # With no argument a ref to a hash of hosts is returned.  Each
394 # hash contains fields as specified in the hosts file.  With an
395 # argument a ref to a single hash is returned with information
396 # for just that host.
397 #
398 sub HostInfoRead
399 {
400     my($s, $host) = @_;
401     my(%hosts, @hdr, @fld);
402     local(*HOST_INFO, *LOCK);
403
404     flock(LOCK, LOCK_EX) if open(LOCK, "$s->{ConfDir}/LOCK");
405     if ( !open(HOST_INFO, "$s->{ConfDir}/hosts") ) {
406         print(STDERR "Can't open $s->{ConfDir}/hosts\n");
407         close(LOCK);
408         return {};
409     }
410     binmode(HOST_INFO);
411     while ( <HOST_INFO> ) {
412         s/[\n\r]+//;
413         s/#.*//;
414         s/\s+$//;
415         next if ( /^\s*$/ || !/^([\w\.\\-]+\s+.*)/ );
416         #
417         # Split on white space, except if preceded by \
418         # using zero-width negative look-behind assertion
419         # (always wanted to use one of those).
420         #
421         @fld = split(/(?<!\\)\s+/, $1);
422         #
423         # Remove any \
424         #
425         foreach ( @fld ) {
426             s{\\(\s)}{$1}g;
427         }
428         if ( @hdr ) {
429             if ( defined($host) ) {
430                 next if ( lc($fld[0]) ne lc($host) );
431                 @{$hosts{$fld[0]}}{@hdr} = @fld;
432                 close(HOST_INFO);
433                 close(LOCK);
434                 return \%hosts;
435             } else {
436                 @{$hosts{$fld[0]}}{@hdr} = @fld;
437             }
438         } else {
439             @hdr = @fld;
440         }
441     }
442     close(HOST_INFO);
443     close(LOCK);
444     return \%hosts;
445 }
446
447 #
448 # Writes new hosts information to the hosts file in $s->{ConfDir}/hosts.
449 # With no argument a ref to a hash of hosts is returned.  Each
450 # hash contains fields as specified in the hosts file.  With an
451 # argument a ref to a single hash is returned with information
452 # for just that host.
453 #
454 sub HostInfoWrite
455 {
456     my($s, $hosts) = @_;
457     my($gotHdr, @fld, $hostText, $contents);
458     local(*HOST_INFO);
459
460     if ( !open(HOST_INFO, "$s->{ConfDir}/hosts") ) {
461         return "Can't open $s->{ConfDir}/hosts";
462     }
463     foreach my $host ( keys(%$hosts) ) {
464         my $name = "$hosts->{$host}{host}";
465         my $rest = "\t$hosts->{$host}{dhcp}"
466                  . "\t$hosts->{$host}{user}"
467                  . "\t$hosts->{$host}{moreUsers}";
468         $name =~ s/ /\\ /g;
469         $rest =~ s/ //g;
470         $hostText->{$host} = $name . $rest;
471     }
472     binmode(HOST_INFO);
473     while ( <HOST_INFO> ) {
474         s/[\n\r]+//;
475         if ( /^\s*$/ || /^\s*#/ ) {
476             $contents .= $_ . "\n";
477             next;
478         }
479         if ( !$gotHdr ) {
480             $contents .= $_ . "\n";
481             $gotHdr = 1;
482             next;
483         }
484         @fld = split(/(?<!\\)\s+/, $1);
485         #
486         # Remove any \
487         #
488         foreach ( @fld ) {
489             s{\\(\s)}{$1}g;
490         }
491         if ( defined($hostText->{$fld[0]}) ) {
492             $contents .= $hostText->{$fld[0]} . "\n";
493             delete($hostText->{$fld[0]});
494         }
495     }
496     foreach my $host ( sort(keys(%$hostText)) ) {
497         $contents .= $hostText->{$host} . "\n";
498         delete($hostText->{$host});
499     }
500     close(HOST_INFO);
501
502     #
503     # Write and verify the new host file
504     #
505     return $s->TextFileWrite("$s->{ConfDir}/hosts", $contents);
506 }
507
508 #
509 # Return the mtime of the hosts file
510 #
511 sub HostsMTime
512 {
513     my($s) = @_;
514     return (stat("$s->{ConfDir}/hosts"))[9];
515 }
516
517 1;