06c1e4dd564d2abed75191c79fb1ffab9f9b8c5a
[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 1.6.0_CVS, released 10 Dec 2002.
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, $optX, $smbClientCmd, $logMsg);
83     local(*SMB);
84
85     #
86     # First propagate the PASSWD setting 
87     #
88     $ENV{PASSWD} = $ENV{BPC_SMB_PASSWD} if ( defined($ENV{BPC_SMB_PASSWD}) );
89     $ENV{PASSWD} = $conf->{SmbSharePasswd}
90                                  if ( defined($conf->{SmbSharePasswd}) );
91     if ( !defined($ENV{PASSWD}) ) {
92         $t->{_errStr} = "passwd not set for smbclient";
93         return;
94     }
95     if ( !defined($conf->{SmbClientPath}) || !-x $conf->{SmbClientPath} ) {
96         $t->{_errStr} = '$Conf{SmbClientPath} is not a valid executable';
97         return;
98     }
99     if ( $t->{type} eq "restore" ) {
100         $smbClientCmd =
101               "$conf->{SmbClientPath} '\\\\$t->{host}\\$t->{shareName}'"
102             . "$I_option -U '$conf->{SmbShareUserName}' -E -N -d 1"
103             . " $conf->{SmbClientArgs}"
104             . " -c 'tarmode full' -Tx -";
105         $logMsg = "restore started for share $t->{shareName}";
106     } else {
107         #
108         # Turn $conf->{BackupFilesOnly} and $conf->{BackupFilesExclude}
109         # into a hash of arrays of files
110         #
111         $conf->{SmbShareName} = [ $conf->{SmbShareName} ]
112                         unless ref($conf->{SmbShareName}) eq "ARRAY";
113         foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
114             next if ( !defined($conf->{$param}) );
115             if ( ref($conf->{$param}) eq "ARRAY" ) {
116                 $conf->{$param} = {
117                         $conf->{SmbShareName}[0] => $conf->{$param}
118                 };
119             } elsif ( ref($conf->{$param}) eq "HASH" ) {
120                 # do nothing
121             } else {
122                 $conf->{$param} = {
123                         $conf->{SmbShareName}[0] => [ $conf->{$param} ]
124                 };
125             }
126         }
127         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
128             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
129                 $file =~ s/'/\\'/g;
130                 $fileList .= "'$file' ";
131             }
132         } elsif ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
133             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
134             {
135                 $file =~ s/'/\\'/g;
136                 $fileList .= "'$file' ";
137             }
138             #
139             # Allow simple wildcards in exclude list by specifying "r" option.
140             #
141             $optX = "rX";
142         }
143         if ( $t->{type} eq "full" ) {
144             $smbClientCmd =
145                   "$conf->{SmbClientPath} '\\\\$t->{host}\\$t->{shareName}'"
146                 . "$I_option -U '$conf->{SmbShareUserName}' -E -N -d 1"
147                 . " $conf->{SmbClientArgs}"
148                 . " -c 'tarmode full'"
149                 . " -Tc$optX - $fileList";
150             $logMsg = "full backup started for share $t->{shareName}";
151         } else {
152             my $timeStampFile = "$t->{outDir}/timeStamp.level0";
153             open(LEV0, ">$timeStampFile") && close(LEV0);
154             utime($t->{lastFull} - 3600, $t->{lastFull} - 3600, $timeStampFile);
155             $smbClientCmd =
156                   "$conf->{SmbClientPath} '\\\\$t->{host}\\$t->{shareName}'"
157                 . "$I_option -U '$conf->{SmbShareUserName}' -E -N -d 1"
158                 . " $conf->{SmbClientArgs}"
159                 . " -c 'tarmode full'"
160                 . " -TcN$optX $timeStampFile - $fileList";
161             $logMsg = "incr backup started back to "
162                         . $bpc->timeStamp($t->{lastFull} - 3600, 0)
163                         . "for share $t->{shareName}";
164         }
165     }
166     if ( !defined($t->{xferPid} = open(SMB, "-|")) ) {
167         $t->{_errStr} = "Can't fork to run smbclient";
168         return;
169     }
170     $t->{pipeSMB} = *SMB;
171     if ( !$t->{xferPid} ) {
172         #
173         # This is the smbclient child.
174         #
175         setpgrp 0,0;
176         if ( $t->{type} eq "restore" ) {
177             #
178             # For restores close the write end of the pipe,
179             # clone STDIN from RH, and STDERR to STDOUT
180             #
181             close($t->{pipeWH});
182             close(STDERR);
183             open(STDERR, ">&STDOUT");
184             close(STDIN);
185             open(STDIN, "<&$t->{pipeRH}");
186         } else {
187             #
188             # For backups close the read end of the pipe,
189             # clone STDOUT to WH, STDERR to STDOUT
190             #
191             close($t->{pipeRH});
192             close(STDERR);
193             open(STDERR, ">&STDOUT");
194             open(STDOUT, ">&$t->{pipeWH}");
195         }
196         #
197         # exec smbclient.
198         #
199         exec($smbClientCmd);
200         # should not be reached, but just in case...
201         $t->{_errStr} = "Can't exec $conf->{SmbClientPath}";
202         return;
203     }
204     $t->{XferLOG}->write(\"Running: $smbClientCmd\n");
205     alarm($conf->{SmbClientTimeout});
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->{SmbClientTimeout});
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;