318874aa183ef23108db41706c3b6e2016ef8231
[BackupPC.git] / lib / BackupPC / CGI / Restore.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::CGI::Restore package
4 #
5 # DESCRIPTION
6 #
7 #   This module implements the Restore action for the CGI interface.
8 #
9 # AUTHOR
10 #   Craig Barratt  <cbarratt@users.sourceforge.net>
11 #
12 # COPYRIGHT
13 #   Copyright (C) 2003-2007  Craig Barratt
14 #
15 #   This program is free software; you can redistribute it and/or modify
16 #   it under the terms of the GNU General Public License as published by
17 #   the Free Software Foundation; either version 2 of the License, or
18 #   (at your option) any later version.
19 #
20 #   This program is distributed in the hope that it will be useful,
21 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
22 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 #   GNU General Public License for more details.
24 #
25 #   You should have received a copy of the GNU General Public License
26 #   along with this program; if not, write to the Free Software
27 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28 #
29 #========================================================================
30 #
31 # Version 3.1.0beta0, released 3 Sep 2007.
32 #
33 # See http://backuppc.sourceforge.net.
34 #
35 #========================================================================
36
37 package BackupPC::CGI::Restore;
38
39 use strict;
40 use BackupPC::CGI::Lib qw(:all);
41 use Data::Dumper;
42 use File::Path;
43 use Encode qw/decode_utf8/;
44
45 sub action
46 {
47     my($str, $reply, $content);
48     my $Privileged = CheckPermission($In{host});
49     if ( !$Privileged ) {
50         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_restore_backup_files}}"));
51     }
52     my $host  = $In{host};
53     my $num   = $In{num};
54     my $share = $In{share};
55     my(@fileList, $fileListStr, $hiddenStr, $pathHdr, $badFileCnt);
56     my @Backups = $bpc->BackupInfoRead($host);
57
58     ServerConnect();
59     if ( !defined($Hosts->{$host}) ) {
60         ErrorExit(eval("qq{$Lang->{Bad_host_name}}"));
61     }
62     for ( my $i = 0 ; $i < $In{fcbMax} ; $i++ ) {
63         next if ( !defined($In{"fcb$i"}) );
64         (my $name = $In{"fcb$i"}) =~ s/%([0-9A-F]{2})/chr(hex($1))/eg;
65         $badFileCnt++ if ( $name =~ m{(^|/)\.\.(/|$)} );
66         if ( @fileList == 0 ) {
67             $pathHdr = substr($name, 0, rindex($name, "/"));
68         } else {
69             while ( substr($name, 0, length($pathHdr)) ne $pathHdr ) {
70                 $pathHdr = substr($pathHdr, 0, rindex($pathHdr, "/"));
71             }
72         }
73         push(@fileList, $name);
74         $hiddenStr .= <<EOF;
75 <input type="hidden" name="fcb$i" value="$In{'fcb' . $i}">
76 EOF
77         $name = decode_utf8($name);
78         $fileListStr .= <<EOF;
79 <li> ${EscHTML($name)}
80 EOF
81     }
82     $hiddenStr .= "<input type=\"hidden\" name=\"fcbMax\" value=\"$In{fcbMax}\">\n";
83     $hiddenStr .= "<input type=\"hidden\" name=\"share\" value=\"${EscHTML(decode_utf8($share))}\">\n";
84     $badFileCnt++ if ( $In{pathHdr} =~ m{(^|/)\.\.(/|$)} );
85     $badFileCnt++ if ( $In{num} =~ m{(^|/)\.\.(/|$)} );
86     if ( @fileList == 0 ) {
87         ErrorExit($Lang->{You_haven_t_selected_any_files__please_go_Back_to});
88     }
89     if ( $badFileCnt ) {
90         ErrorExit($Lang->{Nice_try__but_you_can_t_put});
91     }
92     $pathHdr = "/" if ( $pathHdr eq "" );
93     if ( $In{type} != 0 && @fileList == $In{fcbMax} ) {
94         #
95         # All the files in the list were selected, so just restore the
96         # entire parent directory
97         #
98         @fileList = ( $pathHdr );
99     }
100     if ( $In{type} == 0 ) {
101         #
102         # Build list of hosts
103         #
104         my $hostDestSel;
105         my @hosts;
106         foreach my $h ( GetUserHosts(1) ) {
107             my $sel = " selected" if ( $h eq $In{host} );
108             $hostDestSel .= "<option value=\"$h\"$sel>${EscHTML($h)}</option>";
109             push(@hosts, $h);
110         }
111
112         #
113         # Tell the user what options they have
114         #
115         $pathHdr = decode_utf8($pathHdr);
116         $share   = decode_utf8($share);
117         $content = eval("qq{$Lang->{Restore_Options_for__host2}}");
118
119         if ( @hosts == 1 ) {
120             #
121             # Pick up the host's config file
122             #
123             $bpc->ConfigRead($hosts[0]);
124             %Conf = $bpc->Conf();
125         }
126
127         #
128         # Decide if option 1 (direct restore) is available based
129         # on whether the restore command is set.
130         #
131         my $cmd = $Conf{XferMethod} eq "smb" ? $Conf{SmbClientRestoreCmd}
132                 : $Conf{XferMethod} eq "tar" ? $Conf{TarClientRestoreCmd}
133                 : $Conf{XferMethod} eq "archive" ? undef
134                 : $Conf{RsyncRestoreArgs};
135         if ( defined($cmd) ) {
136             $content .= eval(
137                 "qq{$Lang->{Restore_Options_for__host_Option1}}");
138         } else {
139             my $hostDest = $hosts[0];
140             $content .= eval(
141                 "qq{$Lang->{Restore_Options_for__host_Option1_disabled}}");
142         }
143
144         #
145         # Verify that Archive::Zip is available before showing the
146         # zip restore option
147         #
148         if ( eval { require Archive::Zip } ) {
149             $content .= eval("qq{$Lang->{Option_2__Download_Zip_archive}}");
150         } else {
151             $content .= eval("qq{$Lang->{Option_2__Download_Zip_archive2}}");
152         }
153         $content .= eval("qq{$Lang->{Option_3__Download_Zip_archive}}");
154         Header(eval("qq{$Lang->{Restore_Options_for__host}}"), $content);
155         Trailer();
156     } elsif ( $In{type} == 1 ) {
157         #
158         # Provide the selected files via a tar archive.
159         #
160         my @fileListTrim = @fileList;
161         if ( @fileListTrim > 10 ) {
162             @fileListTrim = (@fileListTrim[0..9], '...');
163         }
164         $bpc->ServerMesg("log User $User downloaded tar archive for $host,"
165                        . " backup $num; files were: "
166                        . join(", ", @fileListTrim));
167
168         my @pathOpts;
169         if ( $In{relative} ) {
170             @pathOpts = ("-r", $pathHdr, "-p", "");
171         }
172         print(STDOUT <<EOF);
173 Content-Type: application/x-gtar
174 Content-Transfer-Encoding: binary
175 Content-Disposition: attachment; filename=\"restore.tar\"
176
177 EOF
178         #
179         # Fork the child off and manually copy the output to our stdout.
180         # This is necessary to ensure the output gets to the correct place
181         # under mod_perl.
182         #
183         $bpc->cmdSystemOrEvalLong(["$BinDir/BackupPC_tarCreate",
184                  "-h", $host,
185                  "-n", $num,
186                  "-s", $share,
187                  @pathOpts,
188                  @fileList
189             ],
190             sub { print(@_); },
191             1,                  # ignore stderr
192         );
193     } elsif ( $In{type} == 2 ) {
194         #
195         # Provide the selected files via a zip archive.
196         #
197         my @fileListTrim = @fileList;
198         if ( @fileListTrim > 10 ) {
199             @fileListTrim = (@fileListTrim[0..9], '...');
200         }
201         $bpc->ServerMesg("log User $User downloaded zip archive for $host,"
202                        . " backup $num; files were: "
203                        . join(", ", @fileListTrim));
204
205         my @pathOpts;
206         if ( $In{relative} ) {
207             @pathOpts = ("-r", $pathHdr, "-p", "");
208         }
209         print(STDOUT <<EOF);
210 Content-Type: application/zip
211 Content-Transfer-Encoding: binary
212 Content-Disposition: attachment; filename=\"restore.zip\"
213
214 EOF
215         $In{compressLevel} = 5 if ( $In{compressLevel} !~ /^\d+$/ );
216         #
217         # Fork the child off and manually copy the output to our stdout.
218         # This is necessary to ensure the output gets to the correct place
219         # under mod_perl.
220         #
221         $bpc->cmdSystemOrEvalLong(["$BinDir/BackupPC_zipCreate",
222                  "-h", $host,
223                  "-n", $num,
224                  "-c", $In{compressLevel},
225                  "-s", $share,
226                  @pathOpts,
227                  @fileList
228             ],
229             sub { print(@_); },
230             1,                  # ignore stderr
231         );
232     } elsif ( $In{type} == 3 ) {
233         #
234         # Do restore directly onto host
235         #
236         if ( !defined($Hosts->{$In{hostDest}}) ) {
237             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
238         }
239         if ( !CheckPermission($In{hostDest}) ) {
240             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
241         }
242         #
243         # Pick up the destination host's config file
244         #
245         my $hostDest = $1 if ( $In{hostDest} =~ /(.*)/ );
246         $bpc->ConfigRead($hostDest);
247         %Conf = $bpc->Conf();
248
249         #
250         # Decide if option 1 (direct restore) is available based
251         # on whether the restore command is set.
252         #
253         my $cmd = $Conf{XferMethod} eq "smb" ? $Conf{SmbClientRestoreCmd}
254                 : $Conf{XferMethod} eq "tar" ? $Conf{TarClientRestoreCmd}
255                 : $Conf{XferMethod} eq "archive" ? undef
256                 : $Conf{RsyncRestoreArgs};
257         if ( !defined($cmd) ) {
258             ErrorExit(eval("qq{$Lang->{Restore_Options_for__host_Option1_disabled}}"));
259         }
260
261         $fileListStr = "";
262         foreach my $f ( @fileList ) {
263             my $targetFile = $f;
264             (my $strippedShare = $share) =~ s/^\///;
265             (my $strippedShareDest = $In{shareDest}) =~ s/^\///;
266             substr($targetFile, 0, length($pathHdr)) = "/$In{pathHdr}/";
267             $targetFile =~ s{//+}{/}g;
268             $strippedShareDest = decode_utf8($strippedShareDest);
269             $targetFile = decode_utf8($targetFile);
270             $strippedShare = decode_utf8($strippedShare);
271             $f = decode_utf8($f);
272             $fileListStr .= <<EOF;
273 <tr><td>$host:/$strippedShare$f</td><td>$In{hostDest}:/$strippedShareDest$targetFile</td></tr>
274 EOF
275         }
276         $In{shareDest} = decode_utf8($In{shareDest});
277         $In{pathHdr}   = decode_utf8($In{pathHdr});
278         my $content = eval("qq{$Lang->{Are_you_sure}}");
279         Header(eval("qq{$Lang->{Restore_Confirm_on__host}}"), $content);
280         Trailer();
281     } elsif ( $In{type} == 4 ) {
282         if ( !defined($Hosts->{$In{hostDest}}) ) {
283             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
284         }
285         if ( !CheckPermission($In{hostDest}) ) {
286             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
287         }
288         my $hostDest = $1 if ( $In{hostDest} =~ /(.+)/ );
289         my $ipAddr = ConfirmIPAddress($hostDest);
290         #
291         # Prepare and send the restore request.  We write the request
292         # information using Data::Dumper to a unique file,
293         # $TopDir/pc/$hostDest/restoreReq.$$.n.  We use a file
294         # in case the list of files to restore is very long.
295         #
296         my $reqFileName;
297         for ( my $i = 0 ; ; $i++ ) {
298             $reqFileName = "restoreReq.$$.$i";
299             last if ( !-f "$TopDir/pc/$hostDest/$reqFileName" );
300         }
301         my $inPathHdr = $In{pathHdr};
302         $inPathHdr = "/$inPathHdr" if ( $inPathHdr !~ m{^/} );
303         $inPathHdr = "$inPathHdr/" if ( $inPathHdr !~ m{/$} );
304         my %restoreReq = (
305             # source of restore is hostSrc, #num, path shareSrc/pathHdrSrc
306             num         => $In{num},
307             hostSrc     => $host,
308             shareSrc    => $share,
309             pathHdrSrc  => $pathHdr,
310
311             # destination of restore is hostDest:shareDest/pathHdrDest
312             hostDest    => $hostDest,
313             shareDest   => $In{shareDest},
314             pathHdrDest => $inPathHdr,
315
316             # list of files to restore
317             fileList    => \@fileList,
318
319             # other info
320             user        => $User,
321             reqTime     => time,
322         );
323         my($dump) = Data::Dumper->new(
324                          [  \%restoreReq],
325                          [qw(*RestoreReq)]);
326         $dump->Indent(1);
327         mkpath("$TopDir/pc/$hostDest", 0, 0777)
328                                     if ( !-d "$TopDir/pc/$hostDest" );
329         my $openPath = "$TopDir/pc/$hostDest/$reqFileName";
330         if ( open(REQ, ">", $openPath) ) {
331             binmode(REQ);
332             print(REQ $dump->Dump);
333             close(REQ);
334         } else {
335             ErrorExit(eval("qq{$Lang->{Can_t_open_create__openPath}}"));
336         }
337         $reply = $bpc->ServerMesg("restore ${EscURI($ipAddr)}"
338                         . " ${EscURI($hostDest)} $User $reqFileName");
339         $str = eval("qq{$Lang->{Restore_requested_to_host__hostDest__backup___num}}");
340         my $content = eval("qq{$Lang->{Reply_from_server_was___reply}}");
341         Header(eval("qq{$Lang->{Restore_Requested_on__hostDest}}"), $content);
342         Trailer();
343     }
344 }
345
346 1;