9c6a66be7193a664564ac9d61e3d0d144c1e84f4
[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  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.0.0alpha, released 23 Jan 2006.
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;
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($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         $content .= eval("qq{$Lang->{Restore_Options_for__host2}}");
116
117         if ( @hosts == 1 ) {
118             #
119             # Pick up the host's config file
120             #
121             $bpc->ConfigRead($hosts[0]);
122             %Conf = $bpc->Conf();
123         }
124
125         #
126         # Decide if option 1 (direct restore) is available based
127         # on whether the restore command is set.
128         #
129         my $cmd = $Conf{XferMethod} eq "smb" ? $Conf{SmbClientRestoreCmd}
130                 : $Conf{XferMethod} eq "tar" ? $Conf{TarClientRestoreCmd}
131                 : $Conf{XferMethod} eq "archive" ? undef
132                 : $Conf{RsyncRestoreArgs};
133         if ( defined($cmd) ) {
134             $content .= eval(
135                 "qq{$Lang->{Restore_Options_for__host_Option1}}");
136         } else {
137             my $hostDest = $hosts[0];
138             $content .= eval(
139                 "qq{$Lang->{Restore_Options_for__host_Option1_disabled}}");
140         }
141
142         #
143         # Verify that Archive::Zip is available before showing the
144         # zip restore option
145         #
146         if ( eval { require Archive::Zip } ) {
147             $content .= eval("qq{$Lang->{Option_2__Download_Zip_archive}}");
148         } else {
149             $content .= eval("qq{$Lang->{Option_2__Download_Zip_archive2}}");
150         }
151         $content .= eval("qq{$Lang->{Option_3__Download_Zip_archive}}");
152         Header(eval("qq{$Lang->{Restore_Options_for__host}}"), $content);
153         Trailer();
154     } elsif ( $In{type} == 1 ) {
155         #
156         # Provide the selected files via a tar archive.
157         #
158         my @fileListTrim = @fileList;
159         if ( @fileListTrim > 10 ) {
160             @fileListTrim = (@fileListTrim[0..9], '...');
161         }
162         $bpc->ServerMesg("log User $User downloaded tar archive for $host,"
163                        . " backup $num; files were: "
164                        . join(", ", @fileListTrim));
165
166         my @pathOpts;
167         if ( $In{relative} ) {
168             @pathOpts = ("-r", $pathHdr, "-p", "");
169         }
170         print(STDOUT <<EOF);
171 Content-Type: application/x-gtar
172 Content-Transfer-Encoding: binary
173 Content-Disposition: attachment; filename=\"restore.tar\"
174
175 EOF
176         #
177         # Fork the child off and manually copy the output to our stdout.
178         # This is necessary to ensure the output gets to the correct place
179         # under mod_perl.
180         #
181         $bpc->cmdSystemOrEvalLong(["$BinDir/BackupPC_tarCreate",
182                  "-h", $host,
183                  "-n", $num,
184                  "-s", $share,
185                  @pathOpts,
186                  @fileList
187             ],
188             sub { print(@_); },
189             1,                  # ignore stderr
190         );
191     } elsif ( $In{type} == 2 ) {
192         #
193         # Provide the selected files via a zip archive.
194         #
195         my @fileListTrim = @fileList;
196         if ( @fileListTrim > 10 ) {
197             @fileListTrim = (@fileListTrim[0..9], '...');
198         }
199         $bpc->ServerMesg("log User $User downloaded zip archive for $host,"
200                        . " backup $num; files were: "
201                        . join(", ", @fileListTrim));
202
203         my @pathOpts;
204         if ( $In{relative} ) {
205             @pathOpts = ("-r", $pathHdr, "-p", "");
206         }
207         print(STDOUT <<EOF);
208 Content-Type: application/zip
209 Content-Transfer-Encoding: binary
210 Content-Disposition: attachment; filename=\"restore.zip\"
211
212 EOF
213         $In{compressLevel} = 5 if ( $In{compressLevel} !~ /^\d+$/ );
214         #
215         # Fork the child off and manually copy the output to our stdout.
216         # This is necessary to ensure the output gets to the correct place
217         # under mod_perl.
218         #
219         $bpc->cmdSystemOrEvalLong(["$BinDir/BackupPC_zipCreate",
220                  "-h", $host,
221                  "-n", $num,
222                  "-c", $In{compressLevel},
223                  "-s", $share,
224                  @pathOpts,
225                  @fileList
226             ],
227             sub { print(@_); },
228             1,                  # ignore stderr
229         );
230     } elsif ( $In{type} == 3 ) {
231         #
232         # Do restore directly onto host
233         #
234         if ( !defined($Hosts->{$In{hostDest}}) ) {
235             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
236         }
237         if ( !CheckPermission($In{hostDest}) ) {
238             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
239         }
240         #
241         # Pick up the destination host's config file
242         #
243         my $hostDest = $1 if ( $In{hostDest} =~ /(.*)/ );
244         $bpc->ConfigRead($hostDest);
245         %Conf = $bpc->Conf();
246
247         #
248         # Decide if option 1 (direct restore) is available based
249         # on whether the restore command is set.
250         #
251         my $cmd = $Conf{XferMethod} eq "smb" ? $Conf{SmbClientRestoreCmd}
252                 : $Conf{XferMethod} eq "tar" ? $Conf{TarClientRestoreCmd}
253                 : $Conf{XferMethod} eq "archive" ? undef
254                 : $Conf{RsyncRestoreArgs};
255         if ( !defined($cmd) ) {
256             ErrorExit(eval("qq{$Lang->{Restore_Options_for__host_Option1_disabled}}"));
257         }
258
259         $fileListStr = "";
260         foreach my $f ( @fileList ) {
261             my $targetFile = $f;
262             (my $strippedShare = $share) =~ s/^\///;
263             (my $strippedShareDest = $In{shareDest}) =~ s/^\///;
264             substr($targetFile, 0, length($pathHdr)) = "/$In{pathHdr}/";
265             $targetFile =~ s{//+}{/}g;
266             $strippedShareDest = decode_utf8($strippedShareDest);
267             $targetFile = decode_utf8($targetFile);
268             $strippedShare = decode_utf8($strippedShare);
269             $f = decode_utf8($f);
270             $fileListStr .= <<EOF;
271 <tr><td>$host:/$strippedShare$f</td><td>$In{hostDest}:/$strippedShareDest$targetFile</td></tr>
272 EOF
273         }
274         my $content = eval("qq{$Lang->{Are_you_sure}}");
275         Header(eval("qq{$Lang->{Restore_Confirm_on__host}}"), $content);
276         Trailer();
277     } elsif ( $In{type} == 4 ) {
278         if ( !defined($Hosts->{$In{hostDest}}) ) {
279             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
280         }
281         if ( !CheckPermission($In{hostDest}) ) {
282             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
283         }
284         my $hostDest = $1 if ( $In{hostDest} =~ /(.+)/ );
285         my $ipAddr = ConfirmIPAddress($hostDest);
286         #
287         # Prepare and send the restore request.  We write the request
288         # information using Data::Dumper to a unique file,
289         # $TopDir/pc/$hostDest/restoreReq.$$.n.  We use a file
290         # in case the list of files to restore is very long.
291         #
292         my $reqFileName;
293         for ( my $i = 0 ; ; $i++ ) {
294             $reqFileName = "restoreReq.$$.$i";
295             last if ( !-f "$TopDir/pc/$hostDest/$reqFileName" );
296         }
297         my $inPathHdr = $In{pathHdr};
298         $inPathHdr = "/$inPathHdr" if ( $inPathHdr !~ m{^/} );
299         $inPathHdr = "$inPathHdr/" if ( $inPathHdr !~ m{/$} );
300         my %restoreReq = (
301             # source of restore is hostSrc, #num, path shareSrc/pathHdrSrc
302             num         => $In{num},
303             hostSrc     => $host,
304             shareSrc    => $share,
305             pathHdrSrc  => $pathHdr,
306
307             # destination of restore is hostDest:shareDest/pathHdrDest
308             hostDest    => $hostDest,
309             shareDest   => $In{shareDest},
310             pathHdrDest => $inPathHdr,
311
312             # list of files to restore
313             fileList    => \@fileList,
314
315             # other info
316             user        => $User,
317             reqTime     => time,
318         );
319         my($dump) = Data::Dumper->new(
320                          [  \%restoreReq],
321                          [qw(*RestoreReq)]);
322         $dump->Indent(1);
323         mkpath("$TopDir/pc/$hostDest", 0, 0777)
324                                     if ( !-d "$TopDir/pc/$hostDest" );
325         my $openPath = "$TopDir/pc/$hostDest/$reqFileName";
326         if ( open(REQ, ">", $openPath) ) {
327             binmode(REQ);
328             print(REQ $dump->Dump);
329             close(REQ);
330         } else {
331             ErrorExit(eval("qq{$Lang->{Can_t_open_create__openPath}}"));
332         }
333         $reply = $bpc->ServerMesg("restore ${EscURI($ipAddr)}"
334                         . " ${EscURI($hostDest)} $User $reqFileName");
335         $str = eval("qq{$Lang->{Restore_requested_to_host__hostDest__backup___num}}");
336         my $content = eval("qq{$Lang->{Reply_from_server_was___reply}}");
337         Header(eval("qq{$Lang->{Restore_Requested_on__hostDest}}"), $content);
338         Trailer();
339     }
340 }
341
342 1;