3f88c3c01f928aa21798fd7f899ca0e28a33af4d
[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-2003  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.1.0_CVS, released 3 Jul 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         $t->{fileIncludeHash} = {};
125         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
126             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
127                 push(@fileList, $file);
128                 $t->{fileIncludeHash}{$file} = 1;
129             }
130         } elsif ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
131             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
132             {
133                 push(@fileList, $file);
134             }
135             #
136             # Allow simple wildcards in exclude list by specifying "r" option.
137             #
138             $X_option = "rX";
139         }
140         if ( $t->{type} eq "full" ) {
141             $smbClientCmd = $conf->{SmbClientFullCmd};
142             $logMsg = "full backup started for share $t->{shareName}";
143         } else {
144             $timeStampFile = "$t->{outDir}/timeStamp.level0";
145             open(LEV0, ">", $timeStampFile) && close(LEV0);
146             utime($t->{lastFull} - 3600, $t->{lastFull} - 3600, $timeStampFile);
147             $smbClientCmd = $conf->{SmbClientIncrCmd};
148             $logMsg = "incr backup started back to "
149                         . $bpc->timeStamp($t->{lastFull} - 3600, 0)
150                         . "for share $t->{shareName}";
151         }
152     }
153     my $args = {
154         smbClientPath => $conf->{SmbClientPath},
155         host          => $t->{host},
156         hostIP        => $t->{hostIP},
157         client        => $t->{client},
158         shareName     => $t->{shareName},
159         userName      => $conf->{SmbShareUserName},
160         fileList      => \@fileList,
161         I_option      => $I_option,
162         X_option      => $X_option,
163         timeStampFile => $timeStampFile,
164     };
165     $smbClientCmd = $bpc->cmdVarSubstitute($smbClientCmd, $args);
166
167     if ( !defined($t->{xferPid} = open(SMB, "-|")) ) {
168         $t->{_errStr} = "Can't fork to run smbclient";
169         return;
170     }
171     $t->{pipeSMB} = *SMB;
172     if ( !$t->{xferPid} ) {
173         #
174         # This is the smbclient child.
175         #
176         setpgrp 0,0;
177         if ( $t->{type} eq "restore" ) {
178             #
179             # For restores close the write end of the pipe,
180             # clone STDIN from RH, and STDERR to STDOUT
181             #
182             close($t->{pipeWH});
183             close(STDERR);
184             open(STDERR, ">&STDOUT");
185             close(STDIN);
186             open(STDIN, "<&$t->{pipeRH}");
187         } else {
188             #
189             # For backups close the read end of the pipe,
190             # clone STDOUT to WH, STDERR to STDOUT
191             #
192             close($t->{pipeRH});
193             close(STDERR);
194             open(STDERR, ">&STDOUT");
195             open(STDOUT, ">&$t->{pipeWH}");
196         }
197         #
198         # Run smbclient.
199         #
200         $bpc->cmdExecOrEval($smbClientCmd, $args);
201         # should not be reached, but just in case...
202         $t->{_errStr} = "Can't exec $conf->{SmbClientPath}";
203         return;
204     }
205     my $str = "Running: " . $bpc->execCmd2ShellCmd(@$smbClientCmd) . "\n";
206     $t->{XferLOG}->write(\$str);
207     alarm($conf->{ClientTimeout});
208     $t->{_errStr} = undef;
209     return $logMsg;
210 }
211
212 sub readOutput
213 {
214     my($t, $FDreadRef, $rout) = @_;
215     my $conf = $t->{conf};
216
217     if ( vec($rout, fileno($t->{pipeSMB}), 1) ) {
218         my $mesg;
219         if ( sysread($t->{pipeSMB}, $mesg, 8192) <= 0 ) {
220             vec($$FDreadRef, fileno($t->{pipeSMB}), 1) = 0;
221             close($t->{pipeSMB});
222         } else {
223             $t->{smbOut} .= $mesg;
224         }
225     }
226     while ( $t->{smbOut} =~ /(.*?)[\n\r]+(.*)/s ) {
227         $_ = $1;
228         $t->{smbOut} = $2;
229         $t->{XferLOG}->write(\"$_\n");
230         #
231         # refresh our inactivity alarm
232         #
233         alarm($conf->{ClientTimeout});
234         $t->{lastOutputLine} = $_ if ( !/^$/ );
235         #
236         # This section is highly dependent on the version of smbclient.
237         # If you upgrade Samba, make sure that these regexp are still valid.
238         #
239         if ( /^\s*(-?\d+) \(\s*\d+\.\d kb\/s\) (.*)$/ ) {
240             my $sambaFileSize = $1;
241             my $pcFileName    = $2;
242             (my $fileName = $pcFileName) =~ s/\\/\//g;
243             $sambaFileSize += 1024 * 1024 * 4096 if ( $sambaFileSize < 0 );
244             $fileName =~ s/^\/*//;
245             $t->{byteCnt} += $sambaFileSize;
246             $t->{fileCnt}++;
247         } elsif ( /restore tar file (.*) of size (\d+) bytes/ ) {
248             $t->{byteCnt} += $2;
249             $t->{fileCnt}++;
250         } elsif ( /tar: dumped \d+ files/ ) {
251             $t->{xferOK} = 1;
252         } elsif ( /^tar: restored \d+ files/ ) {
253             $t->{xferOK} = 1;
254         } elsif ( /^read_socket_with_timeout: timeout read. /i ) {
255             $t->{hostAbort} = 1;
256         } elsif ( /^code 0 listing /
257                     || /^code 0 opening /
258                     || /^abandoning restore/i
259                     || /^Error: Looping in FIND_NEXT/i
260                     || /^SUCCESS - 0/i
261                     || /^Call timed out: server did not respond/i
262                     || /^tree connect failed: ERRDOS - ERRnoaccess \(Access denied\.\)/
263                     || /^tree connect failed: NT_STATUS_BAD_NETWORK_NAME/
264                  ) {
265             if ( $t->{hostError} eq "" ) {
266                 $t->{XferLOG}->write(\"This backup will fail because: $_\n");
267                 $t->{hostError} = $_;
268             }
269         } elsif ( /^NT_STATUS_ACCESS_DENIED listing (.*)/
270                || /^ERRDOS - ERRnoaccess \(Access denied\.\) listing (.*)/ ) {
271             my $badDir = $1;
272             $badDir =~ s{\\}{/}g;
273             $badDir =~ s{/+}{/}g;
274             $badDir =~ s{/\*$}{};
275             if ( $t->{hostError} eq ""
276                     && ($badDir eq "" || $t->{fileIncludeHash}{$badDir}) ) {
277                 $t->{XferLOG}->write(\"This backup will fail because: $_\n");
278                 $t->{hostError} ||= $_;
279             }
280         } elsif ( /smb: \\>/
281                 || /^added interface/i
282                 || /^tarmode is now/i
283                 || /^Total bytes written/i
284                 || /^Domain=/i
285                 || /^\([\d\.]* kb\/s\) \(average [\d\.]* kb\/s\)$/i
286                 || /^Getting files newer than/i
287                 || /^\s+directory \\/i
288                 || /^Output is \/dev\/null/i
289                 || /^Timezone is/i ) {
290             # ignore these messages
291         } else {
292             $t->{xferErrCnt}++;
293             $t->{xferBadShareCnt}++ if ( /^ERRDOS - ERRbadshare/ );
294             $t->{xferBadFileCnt}++  if ( /^ERRDOS - ERRbadfile/ );
295             if ( $t->{xferErrCnt} > 50000 ) {
296                 $t->logMsg(
297                       "Too many smbtar errors ($t->{xferErrCnt})... giving up");
298                 $t->{hostError} = "Too many smbtar errors ($t->{xferErrCnt})";
299                 return;
300             }
301             if ( /^Error reading file (.*)\. Got 0 bytes/ ) {
302                 #
303                 # This happens when a Windoze application has
304                 # locked the file.  This is a particular problem
305                 # with MS-Outlook.  smbclient has already written
306                 # the tar header to stdout, so all it can do is to
307                 # write a dummy file with the correct size, but all
308                 # zeros. BackupPC_tarExtract stores these
309                 # zero-content files efficiently as a sparse file,
310                 # or if compression is on the file will be small
311                 # anyhow.  After the dump is done we simply delete
312                 # the file (it is no use) and try to link it to same
313                 # file in any recent backup.
314                 #
315                 my $badFile = $1;
316                 $badFile =~ s{\\}{/}g;
317                 $badFile =~ s{^/}{};
318                 push(@{$t->{badFiles}}, {
319                         share => $t->{shareName},
320                         file  => $badFile
321                     });
322             }
323         }
324     }
325     return 1;
326 }
327
328 sub setSelectMask
329 {
330     my($t, $FDreadRef) = @_;
331
332     vec($$FDreadRef, fileno($t->{pipeSMB}), 1) = 1;
333 }
334
335 sub errStr
336 {
337     my($t) = @_;
338
339     return $t->{_errStr};
340 }
341
342 sub xferPid
343 {
344     my($t) = @_;
345
346     return ($t->{xferPid});
347 }
348
349 sub logMsg
350 {
351     my($t, $msg) = @_;
352
353     push(@{$t->{_logMsg}}, $msg);
354 }
355
356 sub logMsgGet
357 {
358     my($t) = @_;
359
360     return shift(@{$t->{_logMsg}});
361 }
362
363 #
364 # Returns a hash ref giving various status information about
365 # the transfer.
366 #
367 sub getStats
368 {
369     my($t) = @_;
370
371     return { map { $_ => $t->{$_} }
372             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
373                xferOK hostAbort hostError lastOutputLine)
374     };
375 }
376
377 sub getBadFiles
378 {
379     my($t) = @_;
380
381     return @{$t->{badFiles}};
382 }
383
384 1;