* checkin with 3.2.0beta0 release header
[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-2007  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 3.2.0beta0, released 5 April 2009.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Xfer::Smb;
39
40 use strict;
41 use Encode qw/from_to encode/;
42 use base qw(BackupPC::Xfer::Protocol);
43
44 sub useTar
45 {
46     return 1;
47 }
48
49 sub start
50 {
51     my($t) = @_;
52     my $bpc = $t->{bpc};
53     my $conf = $t->{conf};
54     my $I_option = $t->{hostIP} eq $t->{host} ? [] : ['-I', $t->{hostIP}];
55     my(@fileList, $X_option, $smbClientCmd, $logMsg);
56     my($timeStampFile);
57     local(*SMB);
58
59     #
60     # First propagate the PASSWD setting 
61     #
62     $ENV{PASSWD} = $ENV{BPC_SMB_PASSWD} if ( defined($ENV{BPC_SMB_PASSWD}) );
63     $ENV{PASSWD} = $conf->{SmbSharePasswd}
64                                  if ( defined($conf->{SmbSharePasswd}) );
65     if ( !defined($ENV{PASSWD}) ) {
66         $t->{_errStr} = "passwd not set for smbclient";
67         return;
68     }
69     if ( !defined($conf->{SmbClientPath}) || !-x $conf->{SmbClientPath} ) {
70         $t->{_errStr} = '$Conf{SmbClientPath} is not a valid executable';
71         return;
72     }
73     if ( $t->{type} eq "restore" ) {
74         $smbClientCmd = $conf->{SmbClientRestoreCmd};
75         $logMsg = "restore started for share $t->{shareName}";
76     } else {
77         #
78         # Turn $conf->{BackupFilesOnly} and $conf->{BackupFilesExclude}
79         # into a hash of arrays of files, and $conf->{SmbShareName}
80         # to an array
81         #
82         $bpc->backupFileConfFix($conf, "SmbShareName");
83
84         $t->{fileIncludeHash} = {};
85         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
86             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
87                 $file = encode($conf->{ClientCharset}, $file)
88                             if ( $conf->{ClientCharset} ne "" );
89                 push(@fileList, $file);
90                 $t->{fileIncludeHash}{$file} = 1;
91             }
92         } elsif ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
93             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
94             {
95                 $file = encode($conf->{ClientCharset}, $file)
96                             if ( $conf->{ClientCharset} ne "" );
97                 push(@fileList, $file);
98             }
99             #
100             # Allow simple wildcards in exclude list by specifying "r" option.
101             #
102             $X_option = "rX";
103         }
104         if ( $t->{type} eq "full" ) {
105             $smbClientCmd = $conf->{SmbClientFullCmd};
106             $logMsg = "full backup started for share $t->{shareName}";
107         } else {
108             $timeStampFile = "$t->{outDir}/timeStamp.level0";
109             open(LEV0, ">", $timeStampFile) && close(LEV0);
110             utime($t->{incrBaseTime} - 3600, $t->{incrBaseTime} - 3600,
111                   $timeStampFile);
112             $smbClientCmd = $conf->{SmbClientIncrCmd};
113             $logMsg = "incr backup started back to "
114                     . $bpc->timeStamp($t->{incrBaseTime} - 3600, 0)
115                     . " (backup #$t->{incrBaseBkupNum}) for share"
116                     . " $t->{shareName}";
117         }
118     }
119     my $args = {
120         smbClientPath => $conf->{SmbClientPath},
121         host          => $t->{host},
122         hostIP        => $t->{hostIP},
123         client        => $t->{client},
124         shareName     => $t->{shareName},
125         userName      => $conf->{SmbShareUserName},
126         fileList      => \@fileList,
127         I_option      => $I_option,
128         X_option      => $X_option,
129         timeStampFile => $timeStampFile,
130     };
131     from_to($args->{shareName}, "utf8", $conf->{ClientCharset})
132                             if ( $conf->{ClientCharset} ne "" );
133     $smbClientCmd = $bpc->cmdVarSubstitute($smbClientCmd, $args);
134
135     if ( !defined($t->{xferPid} = open(SMB, "-|")) ) {
136         $t->{_errStr} = "Can't fork to run smbclient";
137         return;
138     }
139     $t->{pipeSMB} = *SMB;
140     if ( !$t->{xferPid} ) {
141         #
142         # This is the smbclient child.
143         #
144         setpgrp 0,0;
145         if ( $t->{type} eq "restore" ) {
146             #
147             # For restores close the write end of the pipe,
148             # clone STDIN from RH, and STDERR to STDOUT
149             #
150             close($t->{pipeWH});
151             close(STDERR);
152             open(STDERR, ">&STDOUT");
153             close(STDIN);
154             open(STDIN, "<&$t->{pipeRH}");
155         } else {
156             #
157             # For backups close the read end of the pipe,
158             # clone STDOUT to WH, STDERR to STDOUT
159             #
160             close($t->{pipeRH});
161             close(STDERR);
162             open(STDERR, ">&STDOUT");
163             open(STDOUT, ">&$t->{pipeWH}");
164         }
165         #
166         # Run smbclient.
167         #
168         alarm(0);
169         $bpc->cmdExecOrEval($smbClientCmd, $args);
170         # should not be reached, but just in case...
171         $t->{_errStr} = "Can't exec $conf->{SmbClientPath}";
172         return;
173     }
174     my $str = "Running: " . $bpc->execCmd2ShellCmd(@$smbClientCmd) . "\n";
175     from_to($str, $conf->{ClientCharset}, "utf8")
176                             if ( $conf->{ClientCharset} ne "" );
177     $t->{XferLOG}->write(\$str);
178     alarm($conf->{ClientTimeout});
179     $t->{_errStr} = undef;
180     return $logMsg;
181 }
182
183 sub readOutput
184 {
185     my($t, $FDreadRef, $rout) = @_;
186     my $conf = $t->{conf};
187
188     if ( vec($rout, fileno($t->{pipeSMB}), 1) ) {
189         my $mesg;
190         if ( sysread($t->{pipeSMB}, $mesg, 8192) <= 0 ) {
191             vec($$FDreadRef, fileno($t->{pipeSMB}), 1) = 0;
192             close($t->{pipeSMB});
193         } else {
194             $t->{smbOut} .= $mesg;
195         }
196     }
197     while ( $t->{smbOut} =~ /(.*?)[\n\r]+(.*)/s ) {
198         $_ = $1;
199         $t->{smbOut} = $2;
200         #
201         # ignore the log file time stamps from smbclient introduced
202         # in version 3.0.0 - don't even write them to the log file.
203         #
204         if ( m{^\[\d+/\d+/\d+ +\d+:\d+:\d+.*\] +(client/cli|lib/util_unistr).*\(\d+\)} ) {
205             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 5 );
206             next;
207         }
208         #
209         # refresh our inactivity alarm
210         #
211         alarm($conf->{ClientTimeout}) if ( !$t->{abort} );
212         $t->{lastOutputLine} = $_ if ( !/^$/ );
213
214         from_to($_, $conf->{ClientCharset}, "utf8")
215                             if ( $conf->{ClientCharset} ne "" );
216         #
217         # This section is highly dependent on the version of smbclient.
218         # If you upgrade Samba, make sure that these regexp are still valid.
219         #
220         if ( /^\s*(-?\d+) \(\s*\d+[.,]\d kb\/s\) (.*)$/ ) {
221             my $sambaFileSize = $1;
222             my $pcFileName    = $2;
223             (my $fileName = $pcFileName) =~ s/\\/\//g;
224             $sambaFileSize += 1024 * 1024 * 4096 if ( $sambaFileSize < 0 );
225             $fileName =~ s/^\/*//;
226             $t->{byteCnt} += $sambaFileSize;
227             $t->{fileCnt}++;
228             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 2 );
229         } elsif ( /restore tar file (.*) of size (\d+) bytes/ ) {
230             $t->{byteCnt} += $2;
231             $t->{fileCnt}++;
232             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 1 );
233         } elsif ( /^\s*tar: dumped \d+ files/ ) {
234             $t->{xferOK} = 1;
235             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 0 );
236         } elsif ( /^\s*tar: restored \d+ files/ ) {
237             $t->{xferOK} = 1;
238             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 0 );
239         } elsif ( /^\s*read_socket_with_timeout: timeout read. /i ) {
240             $t->{hostAbort} = 1;
241             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 0 );
242         } elsif ( /^code 0 listing /
243                     || /^\s*code 0 opening /
244                     || /^\s*abandoning restore/i
245                     || /^\s*Error: Looping in FIND_NEXT/i
246                     || /^\s*SUCCESS - 0/i
247                     || /^\s*Call timed out: server did not respond/i
248                     || /^\s*tree connect failed: ERRDOS - ERRnoaccess \(Access denied\.\)/
249                     || /^\s*tree connect failed: NT_STATUS_BAD_NETWORK_NAME/
250                     || /^\s*NT_STATUS_INSUFF_SERVER_RESOURCES listing /
251                  ) {
252             if ( $t->{hostError} eq "" ) {
253                 $t->{XferLOG}->write(\"This backup will fail because: $_\n");
254                 $t->{hostError} = $_;
255             }
256             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 0 );
257         } elsif ( /^\s*NT_STATUS_ACCESS_DENIED listing (.*)/
258                || /^\s*ERRDOS - ERRnoaccess \(Access denied\.\) listing (.*)/ ) {
259             $t->{xferErrCnt}++;
260             my $badDir = $1;
261             $badDir =~ s{\\}{/}g;
262             $badDir =~ s{/+}{/}g;
263             $badDir =~ s{/\*$}{};
264             if ( $t->{hostError} eq ""
265                     && ($badDir eq "" || $t->{fileIncludeHash}{$badDir}) ) {
266                 $t->{XferLOG}->write(\"This backup will fail because: $_\n");
267                 $t->{hostError} ||= $_;
268             }
269             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 0 );
270         } elsif ( /^\s*directory \\/i ) {
271             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 2 );
272         } elsif ( /smb: \\>/
273                 || /^\s*added interface/i
274                 || /^\s*tarmode is now/i
275                 || /^\s*Total bytes written/i
276                 || /^\s*Domain=/i
277                 || /^\([\d\.]* kb\/s\) \(average [\d\.]* kb\/s\)$/i
278                 || /^\s*Getting files newer than/i
279                 || /^\s*restore directory \\/i
280                 || /^\s*Output is \/dev\/null/i
281                 || /^\s*Timezone is/i
282                 || /^\s*tar_re_search set/i
283                 || /^\s*creating lame (up|low)case table/i
284             ) {
285             # ignore these messages
286             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 1 );
287         } else {
288             $t->{xferErrCnt}++;
289             $t->{xferBadShareCnt}++ if ( /^ERRDOS - ERRbadshare/ );
290             $t->{xferBadFileCnt}++  if ( /^ERRDOS - ERRbadfile/ );
291             if ( $t->{xferErrCnt} > 50000 ) {
292                 $t->logMsg(
293                       "Too many smbtar errors ($t->{xferErrCnt})... giving up");
294                 $t->{hostError} = "Too many smbtar errors ($t->{xferErrCnt})";
295                 return;
296             }
297             if ( /^Error reading file (.*)\. Got 0 bytes/ ) {
298                 #
299                 # This happens when a Windoze application has
300                 # locked the file.  This is a particular problem
301                 # with MS-Outlook.  smbclient has already written
302                 # the tar header to stdout, so all it can do is to
303                 # write a dummy file with the correct size, but all
304                 # zeros. BackupPC_tarExtract stores these
305                 # zero-content files efficiently as a sparse file,
306                 # or if compression is on the file will be small
307                 # anyhow.  After the dump is done we simply delete
308                 # the file (it is no use) and try to link it to same
309                 # file in any recent backup.
310                 #
311                 my $badFile = $1;
312                 $badFile =~ s{\\}{/}g;
313                 $badFile =~ s{^/}{};
314                 push(@{$t->{badFiles}}, {
315                         share => $t->{shareName},
316                         file  => $badFile
317                     });
318             }
319             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 1 );
320         }
321     }
322     return 1;
323 }
324
325 sub setSelectMask
326 {
327     my($t, $FDreadRef) = @_;
328
329     vec($$FDreadRef, fileno($t->{pipeSMB}), 1) = 1;
330 }
331
332 1;