Try again; cvs got an error:
[BackupPC.git] / lib / BackupPC / Xfer / Smb.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Xfer::Smb package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Xfer::Smb class for managing
8 #   the SMB (smbclient) transport of backup data from the client.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001  Craig Barratt
15 #
16 #   This program is free software; you can redistribute it and/or modify
17 #   it under the terms of the GNU General Public License as published by
18 #   the Free Software Foundation; either version 2 of the License, or
19 #   (at your option) any later version.
20 #
21 #   This program is distributed in the hope that it will be useful,
22 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
23 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 #   GNU General Public License for more details.
25 #
26 #   You should have received a copy of the GNU General Public License
27 #   along with this program; if not, write to the Free Software
28 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29 #
30 #========================================================================
31 #
32 # Version 2.0.0_CVS, released 18 Jan 2003.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Xfer::Smb;
39
40 use strict;
41
42 sub new
43 {
44     my($class, $bpc, $args) = @_;
45
46     $args ||= {};
47     my $t = bless {
48         bpc       => $bpc,
49         conf      => { $bpc->Conf },
50         host      => "",
51         hostIP    => "",
52         shareName => "",
53         pipeRH    => undef,
54         pipeWH    => undef,
55         badFiles  => [],
56         %$args,
57     }, $class;
58
59     return $t;
60 }
61
62 sub args
63 {
64     my($t, $args) = @_;
65
66     foreach my $arg ( keys(%$args) ) {
67         $t->{$arg} = $args->{$arg};
68     }
69 }
70
71 sub useTar
72 {
73     return 1;
74 }
75
76 sub start
77 {
78     my($t) = @_;
79     my $bpc = $t->{bpc};
80     my $conf = $t->{conf};
81     my $I_option = $t->{hostIP} eq $t->{host} ? [] : ['-I', $t->{hostIP}];
82     my(@fileList, $X_option, $smbClientCmd, $logMsg);
83     my($timeStampFile);
84     local(*SMB);
85
86     #
87     # First propagate the PASSWD setting 
88     #
89     $ENV{PASSWD} = $ENV{BPC_SMB_PASSWD} if ( defined($ENV{BPC_SMB_PASSWD}) );
90     $ENV{PASSWD} = $conf->{SmbSharePasswd}
91                                  if ( defined($conf->{SmbSharePasswd}) );
92     if ( !defined($ENV{PASSWD}) ) {
93         $t->{_errStr} = "passwd not set for smbclient";
94         return;
95     }
96     if ( !defined($conf->{SmbClientPath}) || !-x $conf->{SmbClientPath} ) {
97         $t->{_errStr} = '$Conf{SmbClientPath} is not a valid executable';
98         return;
99     }
100     if ( $t->{type} eq "restore" ) {
101         $smbClientCmd = $conf->{SmbClientRestoreCmd};
102         $logMsg = "restore started for share $t->{shareName}";
103     } else {
104         #
105         # Turn $conf->{BackupFilesOnly} and $conf->{BackupFilesExclude}
106         # into a hash of arrays of files
107         #
108         $conf->{SmbShareName} = [ $conf->{SmbShareName} ]
109                         unless ref($conf->{SmbShareName}) eq "ARRAY";
110         foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
111             next if ( !defined($conf->{$param}) );
112             if ( ref($conf->{$param}) eq "ARRAY" ) {
113                 $conf->{$param} = {
114                         $conf->{SmbShareName}[0] => $conf->{$param}
115                 };
116             } elsif ( ref($conf->{$param}) eq "HASH" ) {
117                 # do nothing
118             } else {
119                 $conf->{$param} = {
120                         $conf->{SmbShareName}[0] => [ $conf->{$param} ]
121                 };
122             }
123         }
124         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
125             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
126                 push(@fileList, $file);
127             }
128         } elsif ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
129             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
130             {
131                 push(@fileList, $file);
132             }
133             #
134             # Allow simple wildcards in exclude list by specifying "r" option.
135             #
136             $X_option = "rX";
137         }
138         if ( $t->{type} eq "full" ) {
139             $smbClientCmd = $conf->{SmbClientFullCmd};
140             $logMsg = "full backup started for share $t->{shareName}";
141         } else {
142             $timeStampFile = "$t->{outDir}/timeStamp.level0";
143             open(LEV0, ">", $timeStampFile) && close(LEV0);
144             utime($t->{lastFull} - 3600, $t->{lastFull} - 3600, $timeStampFile);
145             $smbClientCmd = $conf->{SmbClientIncrCmd};
146             $logMsg = "incr backup started back to "
147                         . $bpc->timeStamp($t->{lastFull} - 3600, 0)
148                         . "for share $t->{shareName}";
149         }
150     }
151     my $args = {
152         smbClientPath => $conf->{SmbClientPath},
153         host          => $t->{host},
154         hostIP        => $t->{hostIP},
155         client        => $t->{client},
156         shareName     => $t->{shareName},
157         userName      => $conf->{SmbShareUserName},
158         fileList      => \@fileList,
159         I_option      => $I_option,
160         X_option      => $X_option,
161         timeStampFile => $timeStampFile,
162     };
163     $smbClientCmd = $bpc->cmdVarSubstitute($smbClientCmd, $args);
164
165     if ( !defined($t->{xferPid} = open(SMB, "-|")) ) {
166         $t->{_errStr} = "Can't fork to run smbclient";
167         return;
168     }
169     $t->{pipeSMB} = *SMB;
170     if ( !$t->{xferPid} ) {
171         #
172         # This is the smbclient child.
173         #
174         setpgrp 0,0;
175         if ( $t->{type} eq "restore" ) {
176             #
177             # For restores close the write end of the pipe,
178             # clone STDIN from RH, and STDERR to STDOUT
179             #
180             close($t->{pipeWH});
181             close(STDERR);
182             open(STDERR, ">&STDOUT");
183             close(STDIN);
184             open(STDIN, "<&$t->{pipeRH}");
185         } else {
186             #
187             # For backups close the read end of the pipe,
188             # clone STDOUT to WH, STDERR to STDOUT
189             #
190             close($t->{pipeRH});
191             close(STDERR);
192             open(STDERR, ">&STDOUT");
193             open(STDOUT, ">&$t->{pipeWH}");
194         }
195         #
196         # Run smbclient.
197         #
198         $bpc->cmdExecOrEval($smbClientCmd, $args);
199         # should not be reached, but just in case...
200         $t->{_errStr} = "Can't exec $conf->{SmbClientPath}";
201         return;
202     }
203     my $str = "Running: " . $bpc->execCmd2ShellCmd(@$smbClientCmd) . "\n";
204     $t->{XferLOG}->write(\$str);
205     alarm($conf->{ClientTimeout});
206     $t->{_errStr} = undef;
207     return $logMsg;
208 }
209
210 sub readOutput
211 {
212     my($t, $FDreadRef, $rout) = @_;
213     my $conf = $t->{conf};
214
215     if ( vec($rout, fileno($t->{pipeSMB}), 1) ) {
216         my $mesg;
217         if ( sysread($t->{pipeSMB}, $mesg, 8192) <= 0 ) {
218             vec($$FDreadRef, fileno($t->{pipeSMB}), 1) = 0;
219             close($t->{pipeSMB});
220         } else {
221             $t->{smbOut} .= $mesg;
222         }
223     }
224     while ( $t->{smbOut} =~ /(.*?)[\n\r]+(.*)/s ) {
225         $_ = $1;
226         $t->{smbOut} = $2;
227         $t->{XferLOG}->write(\"$_\n");
228         #
229         # refresh our inactivity alarm
230         #
231         alarm($conf->{ClientTimeout});
232         $t->{lastOutputLine} = $_ if ( !/^$/ );
233         #
234         # This section is highly dependent on the version of smbclient.
235         # If you upgrade Samba, make sure that these regexp are still valid.
236         #
237         if ( /^\s*(-?\d+) \(\s*\d+\.\d kb\/s\) (.*)$/ ) {
238             my $sambaFileSize = $1;
239             my $pcFileName    = $2;
240             (my $fileName = $pcFileName) =~ s/\\/\//g;
241             $sambaFileSize += 1024 * 1024 * 4096 if ( $sambaFileSize < 0 );
242             $fileName =~ s/^\/*//;
243             $t->{byteCnt} += $sambaFileSize;
244             $t->{fileCnt}++;
245         } elsif ( /restore tar file (.*) of size (\d+) bytes/ ) {
246             $t->{byteCnt} += $2;
247             $t->{fileCnt}++;
248         } elsif ( /tar: dumped \d+ files/ ) {
249             $t->{xferOK} = 1;
250         } elsif ( /^tar: restored \d+ files/ ) {
251             $t->{xferOK} = 1;
252         } elsif ( /^read_socket_with_timeout: timeout read. /i ) {
253             $t->{hostAbort} = 1;
254         } elsif ( /^code 0 listing /
255                     || /^code 0 opening /
256                     || /^abandoning restore/i
257                     || /^Error: Looping in FIND_NEXT/i
258                     || /^SUCCESS - 0/i
259                     || /^Call timed out: server did not respond/i
260                  ) {
261             $t->{hostError} ||= $_;
262         } elsif ( /smb: \\>/
263                 || /^added interface/i
264                 || /^tarmode is now/i
265                 || /^Total bytes written/i
266                 || /^Domain=/i
267                 || /^\([\d\.]* kb\/s\) \(average [\d\.]* kb\/s\)$/i
268                 || /^Getting files newer than/i
269                 || /^\s+directory \\/i
270                 || /^Output is \/dev\/null/i
271                 || /^Timezone is/i ) {
272             # ignore these messages
273         } else {
274             $t->{xferErrCnt}++;
275             $t->{xferBadShareCnt}++ if ( /^ERRDOS - ERRbadshare/ );
276             $t->{xferBadFileCnt}++  if ( /^ERRDOS - ERRbadfile/ );
277             if ( $t->{xferErrCnt} > 50000 ) {
278                 $t->logMsg(
279                       "Too many smbtar errors ($t->{xferErrCnt})... giving up");
280                 $t->{hostError} = "Too many smbtar errors ($t->{xferErrCnt})";
281                 return;
282             }
283             if ( /^Error reading file (.*)\. Got 0 bytes/ ) {
284                 #
285                 # This happens when a Windoze application has
286                 # locked the file.  This is a particular problem
287                 # with MS-Outlook.  smbclient has already written
288                 # the tar header to stdout, so all it can do is to
289                 # write a dummy file with the correct size, but all
290                 # zeros. BackupPC_tarExtract stores these
291                 # zero-content files efficiently as a sparse file,
292                 # or if compression is on the file will be small
293                 # anyhow.  After the dump is done we simply delete
294                 # the file (it is no use) and try to link it to same
295                 # file in any recent backup.
296                 #
297                 my $badFile = $1;
298                 $badFile =~ s{\\}{/}g;
299                 $badFile =~ s{^/}{};
300                 push(@{$t->{badFiles}}, "$t->{shareName}/$badFile");
301             }
302         }
303     }
304     return 1;
305 }
306
307 sub setSelectMask
308 {
309     my($t, $FDreadRef) = @_;
310
311     vec($$FDreadRef, fileno($t->{pipeSMB}), 1) = 1;
312 }
313
314 sub errStr
315 {
316     my($t) = @_;
317
318     return $t->{_errStr};
319 }
320
321 sub xferPid
322 {
323     my($t) = @_;
324
325     return $t->{xferPid};
326 }
327
328 sub logMsg
329 {
330     my($t, $msg) = @_;
331
332     push(@{$t->{_logMsg}}, $msg);
333 }
334
335 sub logMsgGet
336 {
337     my($t) = @_;
338
339     return shift(@{$t->{_logMsg}});
340 }
341
342 #
343 # Returns a hash ref giving various status information about
344 # the transfer.
345 #
346 sub getStats
347 {
348     my($t) = @_;
349
350     return { map { $_ => $t->{$_} }
351             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
352                xferOK hostAbort hostError lastOutputLine)
353     };
354 }
355
356 sub getBadFiles
357 {
358     my($t) = @_;
359
360     return @{$t->{badFiles}};
361 }
362
363 1;