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