- set $dirDisplay to "/" if it is empty during directory browse.
[BackupPC.git] / cgi-bin / BackupPC_Admin
1 #!/bin/perl -T
2 #============================================================= -*-perl-*-w
3 #
4 # BackupPC_Admin: Apache/CGI interface for BackupPC.
5 #
6 # DESCRIPTION
7 #   BackupPC_Admin provides a flexible web interface for BackupPC.
8 #   It is a CGI script that runs under Apache.
9 #
10 #   It requires that Apache pass in $ENV{SCRIPT_NAME} and
11 #   $ENV{REMOTE_USER}. The latter requires .ht_access style
12 #   authentication. Replace the code below if you are using some other
13 #   type of authentication, and have a different way of getting the
14 #   user name.
15 #
16 #   Also, this script needs to run as the BackupPC user.  To accomplish
17 #   this the script is typically installed as setuid to the BackupPC user,
18 #   or it can run under mod_perl with httpd running as the BackupPC user.
19 #
20 # AUTHOR
21 #   Craig Barratt  <cbarratt@users.sourceforge.net>
22 #
23 # COPYRIGHT
24 #   Copyright (C) 2001  Craig Barratt
25 #
26 #   This program is free software; you can redistribute it and/or modify
27 #   it under the terms of the GNU General Public License as published by
28 #   the Free Software Foundation; either version 2 of the License, or
29 #   (at your option) any later version.
30 #
31 #   This program is distributed in the hope that it will be useful,
32 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
33 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34 #   GNU General Public License for more details.
35 #
36 #   You should have received a copy of the GNU General Public License
37 #   along with this program; if not, write to the Free Software
38 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
39 #
40 #========================================================================
41 #
42 # Version 2.0.0beta1, released 30 Mar 2003.
43 #
44 # See http://backuppc.sourceforge.net.
45 #
46 #========================================================================
47
48 use strict;
49 use CGI;
50 use lib "/usr/local/BackupPC/lib";
51 use BackupPC::Lib;
52 use BackupPC::FileZIO;
53 use BackupPC::Attrib qw(:all);
54 use BackupPC::View;
55 use Data::Dumper;
56
57 use vars qw($Cgi %In $MyURL $User %Conf $TopDir $BinDir $bpc);
58 use vars qw(%Status %Info %Jobs @BgQueue @UserQueue @CmdQueue
59             %QueueLen %StatusHost);
60 use vars qw($Hosts $HostsMTime $ConfigMTime $PrivAdmin);
61 use vars qw(%UserEmailInfo $UserEmailInfoMTime %RestoreReq);
62
63 use vars qw ($Lang);
64
65 $Cgi = new CGI;
66 %In = $Cgi->Vars;
67
68 #
69 # We require that Apache pass in $ENV{SCRIPT_NAME} and $ENV{REMOTE_USER}.
70 # The latter requires .ht_access style authentication.  Replace this
71 # code if you are using some other type of authentication, and have
72 # a different way of getting the user name.
73 #
74 $MyURL  = $ENV{SCRIPT_NAME};
75 $User   = $ENV{REMOTE_USER};
76
77 if ( !defined($bpc) ) {
78     ErrorExit($Lang->{BackupPC__Lib__new_failed__check_apache_error_log})
79         if ( !($bpc = BackupPC::Lib->new) );
80     $TopDir = $bpc->TopDir();
81     $BinDir = $bpc->BinDir();
82     %Conf   = $bpc->Conf();
83     $Lang   = $bpc->Lang();
84     $ConfigMTime = $bpc->ConfigMTime();
85 } elsif ( $bpc->ConfigMTime() != $ConfigMTime ) {
86     $bpc->ConfigRead();
87     %Conf   = $bpc->Conf();
88     $ConfigMTime = $bpc->ConfigMTime();
89     $Lang   = $bpc->Lang();
90 }
91
92 #
93 # Clean up %ENV for taint checking
94 #
95 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
96 $ENV{PATH} = $Conf{MyPath};
97
98 #
99 # Verify we are running as the correct user
100 #
101 if ( $Conf{BackupPCUserVerify}
102         && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
103     ErrorExit(eval("qq{$Lang->{Wrong_user__my_userid_is___}}"));
104 }
105
106 if ( !defined($Hosts) || $bpc->HostsMTime() != $HostsMTime ) {
107     $HostsMTime = $bpc->HostsMTime();
108     $Hosts = $bpc->HostInfoRead();
109
110     # turn operators list into a hash for quick lookups
111     foreach my $host (keys %$Hosts) {
112        $Hosts->{$host}{moreUsers} =
113            {map {$_, 1} split(",", $Hosts->{$host}{moreUsers}) }
114     }
115 }
116
117 my %ActionDispatch = (
118     "summary"                    => \&Action_Summary,
119     $Lang->{Start_Incr_Backup}   => \&Action_StartStopBackup,
120     $Lang->{Start_Full_Backup}   => \&Action_StartStopBackup,
121     $Lang->{Stop_Dequeue_Backup} => \&Action_StartStopBackup,
122     "queue"                      => \&Action_Queue,
123     "view"                       => \&Action_View,
124     "LOGlist"                    => \&Action_LOGlist,
125     "emailSummary"               => \&Action_EmailSummary,
126     "browse"                     => \&Action_Browse,
127     $Lang->{Restore}             => \&Action_Restore,
128     "RestoreFile"                => \&Action_RestoreFile,
129     "hostInfo"                   => \&Action_HostInfo,
130     "generalInfo"                => \&Action_GeneralInfo,
131     "restoreInfo"                => \&Action_RestoreInfo,
132 );
133
134 #
135 # Set default actions, then call sub handler
136 #
137 $In{action} ||= "hostInfo"    if ( defined($In{host}) );
138 $In{action}   = "generalInfo" if ( !defined($ActionDispatch{$In{action}}) );
139 $ActionDispatch{$In{action}}();
140 exit(0);
141
142 ###########################################################################
143 # Action handling subroutines
144 ###########################################################################
145
146 sub Action_Summary
147 {
148     my($fullTot, $fullSizeTot, $incrTot, $incrSizeTot, $str,
149        $strNone, $strGood, $hostCntGood, $hostCntNone);
150
151     $hostCntGood = $hostCntNone = 0;
152     GetStatusInfo("hosts");
153     my $Privileged = CheckPermission();
154
155     if ( !$Privileged ) {
156         ErrorExit($Lang->{Only_privileged_users_can_view_PC_summaries} );
157     }
158     foreach my $host ( sort(keys(%Status)) ) {
159         my($fullDur, $incrCnt, $incrAge, $fullSize, $fullRate);
160         my @Backups = $bpc->BackupInfoRead($host);
161         my $fullCnt = $incrCnt = 0;
162         my $fullAge = $incrAge = -1;
163         for ( my $i = 0 ; $i < @Backups ; $i++ ) {
164             if ( $Backups[$i]{type} eq "full" ) {
165                 $fullCnt++;
166                 if ( $fullAge < 0 || $Backups[$i]{startTime} > $fullAge ) {
167                     $fullAge  = $Backups[$i]{startTime};
168                     $fullSize = $Backups[$i]{size} / (1024 * 1024);
169                     $fullDur  = $Backups[$i]{endTime} - $Backups[$i]{startTime};
170                 }
171                 $fullSizeTot += $Backups[$i]{size} / (1024 * 1024);
172             } else {
173                 $incrCnt++;
174                 if ( $incrAge < 0 || $Backups[$i]{startTime} > $incrAge ) {
175                     $incrAge = $Backups[$i]{startTime};
176                 }
177                 $incrSizeTot += $Backups[$i]{size} / (1024 * 1024);
178             }
179         }
180         if ( $fullAge < 0 ) {
181             $fullAge = "";
182             $fullRate = "";
183         } else {
184             $fullAge = sprintf("%.1f", (time - $fullAge) / (24 * 3600));
185             $fullRate = sprintf("%.2f",
186                                 $fullSize / ($fullDur <= 0 ? 1 : $fullDur));
187         }
188         if ( $incrAge < 0 ) {
189             $incrAge = "";
190         } else {
191             $incrAge = sprintf("%.1f", (time - $incrAge) / (24 * 3600));
192         }
193         $fullTot += $fullCnt;
194         $incrTot += $incrCnt;
195         $fullSize = sprintf("%.2f", $fullSize / 1000);
196         if (! $incrAge) { $incrAge = "&nbsp;"; }
197         $str = <<EOF;
198 <tr><td> ${HostLink($host)} </td>
199     <td align="center"> ${UserLink($Hosts->{$host}{user})} </td>
200     <td align="center"> $fullCnt </td>
201     <td align="center"> $fullAge </td>
202     <td align="center"> $fullSize </td>
203     <td align="center"> $fullRate </td>
204     <td align="center"> $incrCnt </td>
205     <td align="center"> $incrAge </td>
206     <td align="center"> $Lang->{$Status{$host}{state}} </td>
207     <td> $Lang->{$Status{$host}{reason}} </td></tr>
208 EOF
209         if ( @Backups == 0 ) {
210             $hostCntNone++;
211             $strNone .= $str;
212         } else {
213             $hostCntGood++;
214             $strGood .= $str;
215         }
216     }
217     $fullSizeTot = sprintf("%.2f", $fullSizeTot / 1000);
218     $incrSizeTot = sprintf("%.2f", $incrSizeTot / 1000);
219     my $now      = timeStamp2(time);
220
221     Header($Lang->{BackupPC__Server_Summary});
222     print eval ("qq{$Lang->{BackupPC_Summary}}");
223
224     Trailer();
225 }
226
227 sub Action_StartStopBackup
228 {
229     my($str, $reply);
230
231     my $start = 1 if ( $In{action} eq $Lang->{Start_Incr_Backup}
232                        || $In{action} eq $Lang->{Start_Full_Backup} );
233     my $doFull = $In{action} eq $Lang->{Start_Full_Backup} ? 1 : 0;
234     my $type = $doFull ? "full" : "incremental";
235     my $host = $In{host};
236     my $Privileged = CheckPermission($host);
237
238     if ( !$Privileged ) {
239         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_stop_or_start_backups}}"));
240     }
241     ServerConnect();
242
243     if ( $In{doit} ) {
244         if ( $start ) {
245             if ( $Hosts->{$host}{dhcp} ) {
246                 $reply = $bpc->ServerMesg("backup $In{hostIP} ${EscURI($host)}"
247                                     . " $User $doFull");
248                 $str = eval("qq{$Lang->{Backup_requested_on_DHCP__host}}");
249             } else {
250                 $reply = $bpc->ServerMesg("backup ${EscURI($host)}"
251                                     . " ${EscURI($host)} $User $doFull");
252                 $str = eval("qq{$Lang->{Backup_requested_on__host_by__User}}");
253             }
254         } else {
255             $reply = $bpc->ServerMesg("stop ${EscURI($host)} $User $In{backoff}");
256             $str = eval("qq{$Lang->{Backup_stopped_dequeued_on__host_by__User}}");
257         }
258
259         Header(eval ("qq{$Lang->{BackupPC__Backup_Requested_on__host}}") );
260         print (eval ("qq{$Lang->{REPLY_FROM_SERVER}}"));
261
262         Trailer();
263     } else {
264         if ( $start ) {
265             my $ipAddr = ConfirmIPAddress($host);
266
267             Header(eval("qq{$Lang->{BackupPC__Start_Backup_Confirm_on__host}}"));
268             print (eval("qq{$Lang->{Are_you_sure_start}}"));
269         } else {
270             my $backoff = "";
271             GetStatusInfo("host(${EscURI($host)})");
272             if ( $StatusHost{backoffTime} > time ) {
273                 $backoff = sprintf("%.1f",
274                                   ($StatusHost{backoffTime} - time) / 3600);
275             }
276             Header($Lang->{BackupPC__Stop_Backup_Confirm_on__host});
277             print (eval ("qq{$Lang->{Are_you_sure_stop}}"));
278         }
279         Trailer();
280     }
281 }
282
283 sub Action_Queue
284 {
285     my($strBg, $strUser, $strCmd);
286
287     GetStatusInfo("queues");
288     my $Privileged = CheckPermission();
289
290     if ( !$Privileged ) {
291         ErrorExit($Lang->{Only_privileged_users_can_view_queues_});
292     }
293
294     while ( @BgQueue ) {
295         my $req = pop(@BgQueue);
296         my($reqTime) = timeStamp2($req->{reqTime});
297         $strBg .= <<EOF;
298 <tr><td> ${HostLink($req->{host})} </td>
299     <td align="center"> $reqTime </td>
300     <td align="center"> $req->{user} </td></tr>
301 EOF
302     }
303     while ( @UserQueue ) {
304         my $req = pop(@UserQueue);
305         my $reqTime = timeStamp2($req->{reqTime});
306         $strUser .= <<EOF;
307 <tr><td> ${HostLink($req->{host})} </td>
308     <td align="center"> $reqTime </td>
309     <td align="center"> $req->{user} </td></tr>
310 EOF
311     }
312     while ( @CmdQueue ) {
313         my $req = pop(@CmdQueue);
314         my $reqTime = timeStamp2($req->{reqTime});
315         (my $cmd = $req->{cmd}) =~ s/$BinDir\///;
316         $strCmd .= <<EOF;
317 <tr><td> ${HostLink($req->{host})} </td>
318     <td align="center"> $reqTime </td>
319     <td align="center"> $req->{user} </td>
320     <td> $cmd </td></tr>
321 EOF
322     }
323     Header($Lang->{BackupPC__Queue_Summary});
324
325     print ( eval ( "qq{$Lang->{Backup_Queue_Summary}}") );
326
327     Trailer();
328 }
329
330 sub Action_View
331 {
332     my $Privileged = CheckPermission($In{host});
333     my $compress = 0;
334     my $fh;
335     my $host = $In{host};
336     my $num  = $In{num};
337     my $type = $In{type};
338     my $linkHosts = 0;
339     my($file, $comment);
340     my $ext = $num ne "" ? ".$num" : "";
341
342     ErrorExit(eval("qq{$Lang->{Invalid_number__num}}")) if ( $num ne "" && $num !~ /^\d+$/ );
343     if ( $type eq "XferLOG" ) {
344         $file = "$TopDir/pc/$host/SmbLOG$ext";
345         $file = "$TopDir/pc/$host/XferLOG$ext" if ( !-f $file && !-f "$file.z");
346     } elsif ( $type eq "XferLOGbad" ) {
347         $file = "$TopDir/pc/$host/SmbLOG.bad";
348         $file = "$TopDir/pc/$host/XferLOG.bad" if ( !-f $file && !-f "$file.z");
349     } elsif ( $type eq "XferErrbad" ) {
350         $file = "$TopDir/pc/$host/SmbLOG.bad";
351         $file = "$TopDir/pc/$host/XferLOG.bad" if ( !-f $file && !-f "$file.z");
352         $comment = "(Extracting only Errors)";
353     } elsif ( $type eq "XferErr" ) {
354         $file = "$TopDir/pc/$host/SmbLOG$ext";
355         $file = "$TopDir/pc/$host/XferLOG$ext" if ( !-f $file && !-f "$file.z");
356         $comment = "(Extracting only Errors)";
357     } elsif ( $type eq "RestoreLOG" ) {
358         $file = "$TopDir/pc/$host/RestoreLOG$ext";
359     } elsif ( $type eq "RestoreErr" ) {
360         $file = "$TopDir/pc/$host/RestoreLOG$ext";
361         $comment = "(Extracting only Errors)";
362     } elsif ( $host ne "" && $type eq "config" ) {
363         $file = "$TopDir/pc/$host/config.pl";
364         $file = "$TopDir/conf/$host.pl"
365                     if ( $host ne "config" && -f "$TopDir/conf/$host.pl"
366                                            && !-f $file );
367     } elsif ( $type eq "docs" ) {
368         $file = "$BinDir/../doc/BackupPC.html";
369         if ( open(LOG, $file) ) {
370             Header($Lang->{BackupPC__Documentation});
371             print while ( <LOG> );
372             close(LOG);
373             Trailer();
374         } else {
375             ErrorExit(eval("qq{$Lang->{Unable_to_open__file__configuration_problem}}"));
376         }
377         return;
378     } elsif ( $type eq "config" ) {
379         $file = "$TopDir/conf/config.pl";
380     } elsif ( $type eq "hosts" ) {
381         $file = "$TopDir/conf/hosts";
382     } elsif ( $host ne "" ) {
383         $file = "$TopDir/pc/$host/LOG$ext";
384     } else {
385         $file = "$TopDir/log/LOG$ext";
386         $linkHosts = 1;
387     }
388     if ( !$Privileged ) {
389         ErrorExit($Lang->{Only_privileged_users_can_view_log_or_config_files});
390     }
391     if ( !-f $file && -f "$file.z" ) {
392         $file .= ".z";
393         $compress = 1;
394     }
395     Header(eval("qq{$Lang->{Backup_PC__Log_File__file}}")  );
396     print( eval ("qq{$Lang->{Log_File__file__comment}}"));
397     if ( defined($fh = BackupPC::FileZIO->open($file, 0, $compress)) ) {
398         my $mtimeStr = $bpc->timeStamp((stat($file))[9], 1);
399
400         print ( eval ("qq{$Lang->{Contents_of_log_file}}"));
401
402         print "<pre>";
403         if ( $type eq "XferErr" || $type eq "XferErrbad"
404                                 || $type eq "RestoreErr" ) {
405             my $skipped;
406             while ( 1 ) {
407                 $_ = $fh->readLine();
408                 if ( $_ eq "" ) {
409                     print(eval ("qq{$Lang->{skipped__skipped_lines}}"))
410                                                     if ( $skipped );
411                     last;
412                 }
413                 if ( /smb: \\>/
414                         || /^\s*(\d+) \(\s*\d+\.\d kb\/s\) (.*)$/
415                         || /^tar: dumped \d+ files/
416                         || /^added interface/i
417                         || /^restore tar file /i
418                         || /^restore directory /i
419                         || /^tarmode is now/i
420                         || /^Total bytes written/i
421                         || /^Domain=/i
422                         || /^Getting files newer than/i
423                         || /^Output is \/dev\/null/
424                         || /^\([\d\.]* kb\/s\) \(average [\d\.]* kb\/s\)$/
425                         || /^\s+directory \\/
426                         || /^Timezone is/
427                         || /^\.\//
428                         || /^  /
429                             ) {
430                     $skipped++;
431                     next;
432                 }
433                 print(eval("qq{$Lang->{skipped__skipped_lines}}"))
434                                                      if ( $skipped );
435                 $skipped = 0;
436                 print ${EscHTML($_)};
437             }
438         } elsif ( $linkHosts ) {
439             while ( 1 ) {
440                 $_ = $fh->readLine();
441                 last if ( $_ eq "" );
442                 my $s = ${EscHTML($_)};
443                 $s =~ s/\b([\w-]+)\b/defined($Hosts->{$1})
444                                         ? ${HostLink($1)} : $1/eg;
445                 print $s;
446             }
447         } elsif ( $type eq "config" ) {
448             while ( 1 ) {
449                 $_ = $fh->readLine();
450                 last if ( $_ eq "" );
451                 # remove any passwords and user names
452                 s/(SmbSharePasswd.*=.*['"]).*(['"])/$1$2/ig;
453                 s/(SmbShareUserName.*=.*['"]).*(['"])/$1$2/ig;
454                 s/(ServerMesgSecret.*=.*['"]).*(['"])/$1$2/ig;
455                 print ${EscHTML($_)};
456             }
457         } else {
458             while ( 1 ) {
459                 $_ = $fh->readLine();
460                 last if ( $_ eq "" );
461                 print ${EscHTML($_)};
462             }
463         }
464         $fh->close();
465     } else {
466         printf( eval("qq{$Lang->{_pre___Can_t_open_log_file__file}}"));
467     }
468     print <<EOF;
469 </pre>
470 EOF
471     Trailer();
472 }
473
474 sub Action_LOGlist
475 {
476     my $Privileged = CheckPermission($In{host});
477
478     if ( !$Privileged ) {
479         ErrorExit($Lang->{Only_privileged_users_can_view_log_files});
480     }
481     my $host = $In{host};
482     my($url0, $hdr, $root, $str);
483     if ( $host ne "" ) {
484         $root = "$TopDir/pc/$host/LOG";
485         $url0 = "&host=${EscURI($host)}";
486         $hdr = "for host $host";
487     } else {
488         $root = "$TopDir/log/LOG";
489         $url0 = "";
490         $hdr = "";
491     }
492     for ( my $i = -1 ; ; $i++ ) {
493         my $url1 = "";
494         my $file = $root;
495         if ( $i >= 0 ) {
496             $file .= ".$i";
497             $url1 = "&num=$i";
498         }
499         $file .= ".z" if ( !-f $file && -f "$file.z" );
500         last if ( !-f $file );
501         my $mtimeStr = $bpc->timeStamp((stat($file))[9], 1);
502         my $size     = (stat($file))[7];
503         $str .= <<EOF;
504 <tr><td> <a href="$MyURL?action=view&type=LOG$url0$url1"><tt>$file</tt></a> </td>
505     <td align="right"> $size </td>
506     <td> $mtimeStr </td></tr>
507 EOF
508     }
509     Header($Lang->{BackupPC__Log_File_History});
510     print (eval("qq{$Lang->{Log_File_History__hdr}}"));
511     Trailer();
512 }
513
514 sub Action_EmailSummary
515 {
516     my $Privileged = CheckPermission();
517
518     if ( !$Privileged ) {
519         ErrorExit($Lang->{Only_privileged_users_can_view_email_summaries});
520     }
521     GetStatusInfo("hosts");
522     ReadUserEmailInfo();
523     my(%EmailStr, $str);
524     foreach my $u ( keys(%UserEmailInfo) ) {
525         next if ( !defined($UserEmailInfo{$u}{lastTime}) );
526         my $emailTimeStr = timeStamp2($UserEmailInfo{$u}{lastTime});
527         $EmailStr{$UserEmailInfo{$u}{lastTime}} .= <<EOF;
528 <tr><td>${UserLink($u)} </td>
529     <td>${HostLink($UserEmailInfo{$u}{lastHost})} </td>
530     <td>$emailTimeStr </td>
531     <td>$UserEmailInfo{$u}{lastSubj} </td></tr>
532 EOF
533     }
534     foreach my $t ( sort({$b <=> $a} keys(%EmailStr)) ) {
535         $str .= $EmailStr{$t};
536     }
537     Header($Lang->{Email_Summary});
538     print (eval("qq{$Lang->{Recent_Email_Summary}}"));
539     Trailer();
540 }
541
542 sub Action_Browse
543 {
544     my $Privileged = CheckPermission($In{host});
545     my($i, $dirStr, $fileStr, $attr);
546     my $checkBoxCnt = 0;
547
548     if ( !$Privileged ) {
549         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_browse_backup_files}}"));
550     }
551     my $host  = $In{host};
552     my $num   = $In{num};
553     my $share = $In{share};
554     my $dir   = $In{dir};
555
556     ErrorExit($Lang->{Empty_host_name}) if ( $host eq "" );
557     #
558     # Find the requested backup and the previous filled backup
559     #
560     my @Backups = $bpc->BackupInfoRead($host);
561     for ( $i = 0 ; $i < @Backups ; $i++ ) {
562         last if ( $Backups[$i]{num} == $num );
563     }
564     if ( $i >= @Backups ) {
565         ErrorExit("Backup number $num for host ${EscHTML($host)} does"
566                 . " not exist.");
567     }
568     my $backupTime = timeStamp2($Backups[$i]{startTime});
569     my $backupAge = sprintf("%.1f", (time - $Backups[$i]{startTime})
570                                     / (24 * 3600));
571     my $view = BackupPC::View->new($bpc, $host, \@Backups);
572
573     if ( $dir eq "" || $dir eq "." || $dir eq ".." ) {
574         $attr = $view->dirAttrib($num, "", "");
575         if ( keys(%$attr) > 0 ) {
576             $share = (sort(keys(%$attr)))[0];
577             $dir   = '/';
578         } else {
579             ErrorExit(eval("qq{$Lang->{Directory___EscHTML}}"));
580         }
581     }
582     $dir = "/$dir" if ( $dir !~ /^\// );
583     my $relDir  = $dir;
584     my $currDir = undef;
585
586     #
587     # Loop up the directory tree until we hit the top.
588     #
589     my(@DirStrPrev);
590     while ( 1 ) {
591         my($fLast, $fLastum, @DirStr);
592
593         $attr = $view->dirAttrib($num, $share, $relDir);
594         if ( !defined($attr) ) {
595             ErrorExit(eval("qq{$Lang->{Can_t_browse_bad_directory_name2}}"));
596         }
597
598         my $fileCnt = 0;          # file counter
599         $fLast = $dirStr = "";
600
601         #
602         # Loop over each of the files in this directory
603         #
604         foreach my $f ( sort(keys(%$attr)) ) {
605             my($dirOpen, $gotDir, $imgStr, $img, $path);
606             my $fURI = $f;                             # URI escaped $f
607             my $shareURI = $share;                     # URI escaped $share
608             if ( $relDir eq "" ) {
609                 $path = "/$f";
610             } else {
611                 ($path = "$relDir/$f") =~ s{//+}{/}g;
612             }
613             if ( $shareURI eq "" ) {
614                 $shareURI = $f;
615                 $path  = "/";
616             }
617             $path =~ s{^/+}{/};
618             $path     =~ s/([^\w.\/-])/uc sprintf("%%%02X", ord($1))/eg;
619             $fURI     =~ s/([^\w.\/-])/uc sprintf("%%%02X", ord($1))/eg;
620             $shareURI =~ s/([^\w.\/-])/uc sprintf("%%%02X", ord($1))/eg;
621             $dirOpen  = 1 if ( defined($currDir) && $f eq $currDir );
622             if ( $attr->{$f}{type} == BPC_FTYPE_DIR ) {
623                 #
624                 # Display directory if it exists in current backup.
625                 # First find out if there are subdirs
626                 #
627                 my($bold, $unbold, $BGcolor);
628                 $img |= 1 << 6;
629                 $img |= 1 << 5 if ( $attr->{$f}{nlink} > 2 );
630                 if ( $dirOpen ) {
631                     $bold = "<b>";
632                     $unbold = "</b>";
633                     $img |= 1 << 2;
634                     $img |= 1 << 3 if ( $attr->{$f}{nlink} > 2 );
635                 }
636                 my $imgFileName = sprintf("%07b.gif", $img);
637                 $imgStr = "<img src=\"$Conf{CgiImageDirURL}/$imgFileName\" align=\"absmiddle\" width=\"9\" height=\"19\" border=\"0\">";
638                 if ( "$relDir/$f" eq $dir ) {
639                     $BGcolor = " bgcolor=\"$Conf{CgiHeaderBgColor}\"";
640                 } else {
641                     $BGcolor = "";
642                 }
643                 my $dirName = $f;
644                 $dirName =~ s/ /&nbsp;/g;
645                 push(@DirStr, {needTick => 1,
646                                tdArgs   => $BGcolor,
647                                link     => <<EOF});
648 <a href="$MyURL?action=browse&host=${EscURI($host)}&num=$num&share=$shareURI&dir=$path">$imgStr</a><a href="$MyURL?action=browse&host=${EscURI($host)}&num=$num&share=$shareURI&dir=$path" style="font-size:13px;font-family:arial;text-decoration:none;line-height:15px">&nbsp;$bold$dirName$unbold</a></td></tr>
649 EOF
650                 $fileCnt++;
651                 $gotDir = 1;
652                 if ( $dirOpen ) {
653                     my($lastTick, $doneLastTick);
654                     foreach my $d ( @DirStrPrev ) {
655                         $lastTick = $d if ( $d->{needTick} );
656                     }
657                     $doneLastTick = 1 if ( !defined($lastTick) );
658                     foreach my $d ( @DirStrPrev ) {
659                         $img = 0;
660                         if  ( $d->{needTick} ) {
661                             $img |= 1 << 0;
662                         }
663                         if ( $d == $lastTick ) {
664                             $img |= 1 << 4;
665                             $doneLastTick = 1;
666                         } elsif ( !$doneLastTick ) {
667                             $img |= 1 << 3 | 1 << 4;
668                         }
669                         my $imgFileName = sprintf("%07b.gif", $img);
670                         $imgStr = "<img src=\"$Conf{CgiImageDirURL}/$imgFileName\" align=\"absmiddle\" width=\"9\" height=\"19\" border=\"0\">";
671                         push(@DirStr, {needTick => 0,
672                                        tdArgs   => $d->{tdArgs},
673                                        link     => $imgStr . $d->{link}
674                         });
675                     }
676                 }
677             }
678             if ( $relDir eq $dir ) {
679                 #
680                 # This is the selected directory, so display all the files
681                 #
682                 my $attrStr;
683                 if ( defined($a = $attr->{$f}) ) {
684                     my $mtimeStr = $bpc->timeStamp($a->{mtime});
685                     # UGH -> fix this
686                     my $typeStr  = BackupPC::Attrib::fileType2Text(undef,
687                                                                    $a->{type});
688                     my $modeStr  = sprintf("0%o", $a->{mode} & 07777);
689                     $attrStr .= <<EOF;
690     <td align="center">$typeStr</td>
691     <td align="center">$modeStr</td>
692     <td align="center">$a->{backupNum}</td>
693     <td align="right">$a->{size}</td>
694     <td align="right">$mtimeStr</td>
695 </tr>
696 EOF
697                 } else {
698                     $attrStr .= "<td colspan=\"5\" align=\"center\"> </td>\n";
699                 }
700                 (my $fDisp = "${EscHTML($f)}") =~ s/ /&nbsp;/g;
701                 if ( $gotDir ) {
702                     $fileStr .= <<EOF;
703 <tr bgcolor="#ffffcc"><td><input type="checkbox" name="fcb$checkBoxCnt" value="$path">&nbsp;<a href="$MyURL?action=browse&host=${EscURI($host)}&num=$num&share=$shareURI&dir=$path">$fDisp</a></td>
704 $attrStr
705 </tr>
706 EOF
707                 } else {
708                     $fileStr .= <<EOF;
709 <tr bgcolor="#ffffcc"><td><input type="checkbox" name="fcb$checkBoxCnt" value="$path">&nbsp;<a href="$MyURL?action=RestoreFile&host=${EscURI($host)}&num=$num&share=$shareURI&dir=$path">$fDisp</a></td>
710 $attrStr
711 </tr>
712 EOF
713                 }
714                 $checkBoxCnt++;
715             }
716         }
717         @DirStrPrev = @DirStr;
718         last if ( $relDir eq "" && $share eq "" );
719         # 
720         # Prune the last directory off $relDir, or at the very end
721         # do the top-level directory.
722         #
723         if ( $relDir eq "" || $relDir eq "/" || $relDir !~ /(.*)\/(.*)/ ) {
724             $currDir = $share;
725             $share = "";
726             $relDir = "";
727         } else {
728             $relDir  = $1;
729             $currDir = $2;
730         }
731     }
732     $share = $currDir;
733     my $dirDisplay = "$share/$dir";
734     $dirDisplay =~ s{//+}{/}g;
735     $dirDisplay =~ s{/+$}{}g;
736     $dirDisplay = "/" if ( $dirDisplay eq "" );
737     my $filledBackup;
738
739     if ( (my @mergeNums = @{$view->mergeNums}) > 1 ) {
740         shift(@mergeNums);
741         my $numF = join(", #", @mergeNums);
742         $filledBackup = eval("qq{$Lang->{This_display_is_merged_with_backup}}");
743     }
744     Header(eval("qq{$Lang->{Browse_backup__num_for__host}}"));
745
746     foreach my $d ( @DirStrPrev ) {
747         $dirStr .= "<tr><td$d->{tdArgs}>$d->{link}\n";
748     }
749
750     ### hide checkall button if there are no files
751     my ($topCheckAll, $checkAll, $fileHeader);
752     if ( $fileStr ) {
753         $fileHeader = eval("qq{$Lang->{fileHeader}}");
754
755         $checkAll = $Lang->{checkAll};
756
757         # and put a checkall box on top if there are at least 20 files
758         if ( $checkBoxCnt >= 20 ) {
759             $topCheckAll = $checkAll;
760             $topCheckAll =~ s{allFiles}{allFilestop}g;
761         }
762     } else {
763         $fileStr = eval("qq{$Lang->{The_directory_is_empty}}");
764     }
765     my @otherDirs;
766     foreach my $i ( $view->backupList($share, $dir) ) {
767         my $path = $dir;
768         my $shareURI = $share;
769         $path =~ s/([^\w.\/-])/uc sprintf("%%%02x", ord($1))/eg;
770         $shareURI =~ s/([^\w.\/-])/uc sprintf("%%%02x", ord($1))/eg;
771         push(@otherDirs, "<a href=\"$MyURL?action=browse&host=${EscURI($host)}&num=$i"
772                        . "&share=$shareURI&dir=$path\">$i</a>");
773
774     }
775     if ( @otherDirs ) {
776         my $otherDirs  = join(",\n", @otherDirs);
777         $filledBackup .= eval("qq{$Lang->{Visit_this_directory_in_backup}}");
778     }
779     print (eval("qq{$Lang->{Backup_browse_for__host}}"));
780     Trailer();
781 }
782
783 sub Action_Restore
784 {
785     my($str, $reply);
786     my $Privileged = CheckPermission($In{host});
787     if ( !$Privileged ) {
788         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_restore_backup_files}}"));
789     }
790     my $host  = $In{host};
791     my $num   = $In{num};
792     my $share = $In{share};
793     my(@fileList, $fileListStr, $hiddenStr, $pathHdr, $badFileCnt);
794     my @Backups = $bpc->BackupInfoRead($host);
795
796     ServerConnect();
797     if ( !defined($Hosts->{$host}) ) {
798         ErrorExit(eval("qq{$Lang->{Bad_host_name}}"));
799     }
800     for ( my $i = 0 ; $i < $In{fcbMax} ; $i++ ) {
801         next if ( !defined($In{"fcb$i"}) );
802         (my $name = $In{"fcb$i"}) =~ s/%([0-9A-F]{2})/chr(hex($1))/eg;
803         $badFileCnt++ if ( $name =~ m{(^|/)\.\.(/|$)} );
804         if ( @fileList == 0 ) {
805             $pathHdr = $name;
806         } else {
807             while ( substr($name, 0, length($pathHdr)) ne $pathHdr ) {
808                 $pathHdr = substr($pathHdr, 0, rindex($pathHdr, "/"));
809             }
810         }
811         push(@fileList, $name);
812         $hiddenStr .= <<EOF;
813 <input type="hidden" name="fcb$i" value="$In{'fcb' . $i}">
814 EOF
815         $fileListStr .= <<EOF;
816 <li> ${EscHTML($name)}
817 EOF
818     }
819     $hiddenStr .= "<input type=\"hidden\" name=\"fcbMax\" value=\"$In{fcbMax}\">\n";
820     $hiddenStr .= "<input type=\"hidden\" name=\"share\" value=\"${EscHTML($share)}\">\n";
821     $badFileCnt++ if ( $In{pathHdr} =~ m{(^|/)\.\.(/|$)} );
822     $badFileCnt++ if ( $In{num} =~ m{(^|/)\.\.(/|$)} );
823     if ( @fileList == 0 ) {
824         ErrorExit($Lang->{You_haven_t_selected_any_files__please_go_Back_to});
825     }
826     if ( $badFileCnt ) {
827         ErrorExit($Lang->{Nice_try__but_you_can_t_put});
828     }
829     if ( @fileList == 1 ) {
830         $pathHdr =~ s/(.*)\/.*/$1/;
831     }
832     $pathHdr = "/" if ( $pathHdr eq "" );
833     if ( $In{type} != 0 && @fileList == $In{fcbMax} ) {
834         #
835         # All the files in the list were selected, so just restore the
836         # entire parent directory
837         #
838         @fileList = ( $pathHdr );
839     }
840     if ( $In{type} == 0 ) {
841         #
842         # Tell the user what options they have
843         #
844         Header(eval("qq{$Lang->{Restore_Options_for__host}}"));
845         print(eval("qq{$Lang->{Restore_Options_for__host2}}"));
846
847         #
848         # Verify that Archive::Zip is available before showing the
849         # zip restore option
850         #
851         if ( eval { require Archive::Zip } ) {
852             print (eval("qq{$Lang->{Option_2__Download_Zip_archive}}"));
853         } else {
854             print (eval("qq{$Lang->{Option_2__Download_Zip_archive2}}"));
855         }
856         print (eval("qq{$Lang->{Option_3__Download_Zip_archive}}"));
857         Trailer();
858     } elsif ( $In{type} == 1 ) {
859         #
860         # Provide the selected files via a tar archive.
861         #
862         # We no longer use fork/exec (as in v1.5.0) since some mod_perls
863         # do not correctly preserve the stdout connection to the client
864         # browser, so we execute BackupPC_tarCreate in-line.
865         #
866         my @fileListTrim = @fileList;
867         if ( @fileListTrim > 10 ) {
868             @fileListTrim = (@fileListTrim[0..9], '...');
869         }
870         $bpc->ServerMesg(eval("qq{$Lang->{log_User__User_downloaded_tar_archive_for__host}}"));
871
872         my @pathOpts;
873         if ( $In{relative} ) {
874             @pathOpts = ("-r", $pathHdr, "-p", "");
875         }
876         #
877         # We use syswrite since BackupPC_tarCreate uses syswrite too.
878         # Need to test this with mod_perl: PaulL says it doesn't work.
879         #
880         syswrite(STDOUT, <<EOF);
881 Content-Type: application/x-gtar
882 Content-Transfer-Encoding: binary
883 Content-Disposition: attachment; filename=\"restore.tar\"
884
885 EOF
886         local(@ARGV);
887         @ARGV = (
888              "-h", $host,
889              "-n", $num,
890              "-s", $share,
891              @pathOpts,
892              @fileList
893         );
894         do "$BinDir/BackupPC_tarCreate";
895     } elsif ( $In{type} == 2 ) {
896         #
897         # Provide the selected files via a zip archive.
898         #
899         # We no longer use fork/exec (as in v1.5.0) since some mod_perls
900         # do not correctly preserve the stdout connection to the client
901         # browser, so we execute BackupPC_tarCreate in-line.
902         #
903         my @fileListTrim = @fileList;
904         if ( @fileListTrim > 10 ) {
905             @fileListTrim = (@fileListTrim[0..9], '...');
906         }
907         $bpc->ServerMesg(eval("qq{$Lang->{log_User__User_downloaded_zip_archive_for__host}}"));
908
909         my @pathOpts;
910         if ( $In{relative} ) {
911             @pathOpts = ("-r", $pathHdr, "-p", "");
912         }
913         #
914         # We use syswrite since BackupPC_tarCreate uses syswrite too.
915         # Need to test this with mod_perl: PaulL says it doesn't work.
916         #
917         syswrite(STDOUT, <<EOF);
918 Content-Type: application/zip
919 Content-Transfer-Encoding: binary
920 Content-Disposition: attachment; filename=\"restore.zip\"
921
922 EOF
923         $In{compressLevel} = 5 if ( $In{compressLevel} !~ /^\d+$/ );
924         local(@ARGV);
925         @ARGV = (
926              "-h", $host,
927              "-n", $num,
928              "-c", $In{compressLevel},
929              "-s", $share,
930              @pathOpts,
931              @fileList
932         );
933         do "$BinDir/BackupPC_zipCreate";
934     } elsif ( $In{type} == 3 ) {
935         #
936         # Do restore directly onto host
937         #
938         if ( !defined($Hosts->{$In{hostDest}}) ) {
939             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
940         }
941         if ( !CheckPermission($In{hostDest}) ) {
942             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
943         }
944         $fileListStr = "";
945         foreach my $f ( @fileList ) {
946             my $targetFile = $f;
947             (my $strippedShare = $share) =~ s/^\///;
948             (my $strippedShareDest = $In{shareDest}) =~ s/^\///;
949             substr($targetFile, 0, length($pathHdr)) = $In{pathHdr};
950             $fileListStr .= <<EOF;
951 <tr><td>$host:/$strippedShare$f</td><td>$In{hostDest}:/$strippedShareDest$targetFile</td></tr>
952 EOF
953         }
954         Header(eval("qq{$Lang->{Restore_Confirm_on__host}}"));
955         print(eval("qq{$Lang->{Are_you_sure}}"));
956         Trailer();
957     } elsif ( $In{type} == 4 ) {
958         if ( !defined($Hosts->{$In{hostDest}}) ) {
959             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
960         }
961         if ( !CheckPermission($In{hostDest}) ) {
962             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
963         }
964         my $hostDest = $1 if ( $In{hostDest} =~ /(.+)/ );
965         my $ipAddr = ConfirmIPAddress($hostDest);
966         #
967         # Prepare and send the restore request.  We write the request
968         # information using Data::Dumper to a unique file,
969         # $TopDir/pc/$hostDest/restoreReq.$$.n.  We use a file
970         # in case the list of files to restore is very long.
971         #
972         my $reqFileName;
973         for ( my $i = 0 ; ; $i++ ) {
974             $reqFileName = "restoreReq.$$.$i";
975             last if ( !-f "$TopDir/pc/$hostDest/$reqFileName" );
976         }
977         my %restoreReq = (
978             # source of restore is hostSrc, #num, path shareSrc/pathHdrSrc
979             num         => $In{num},
980             hostSrc     => $host,
981             shareSrc    => $share,
982             pathHdrSrc  => $pathHdr,
983
984             # destination of restore is hostDest:shareDest/pathHdrDest
985             hostDest    => $hostDest,
986             shareDest   => $In{shareDest},
987             pathHdrDest => $In{pathHdr},
988
989             # list of files to restore
990             fileList    => \@fileList,
991
992             # other info
993             user        => $User,
994             reqTime     => time,
995         );
996         my($dump) = Data::Dumper->new(
997                          [  \%restoreReq],
998                          [qw(*RestoreReq)]);
999         $dump->Indent(1);
1000         if ( open(REQ, ">$TopDir/pc/$hostDest/$reqFileName") ) {
1001             print(REQ $dump->Dump);
1002             close(REQ);
1003         } else {
1004             ErrorExit(eval("qq{$Lang->{Can_t_open_create}}"));
1005         }
1006         $reply = $bpc->ServerMesg("restore ${EscURI($ipAddr)}"
1007                         . " ${EscURI($hostDest)} $User $reqFileName");
1008         $str = eval("qq{$Lang->{Restore_requested_to_host__hostDest__backup___num}}");
1009         Header(eval("qq{$Lang->{Restore_Requested_on__hostDest}}"));
1010         print (eval("qq{$Lang->{Reply_from_server_was___reply}}"));
1011         Trailer();
1012     }
1013 }
1014
1015 sub Action_RestoreFile
1016 {
1017     restoreFile($In{host}, $In{num}, $In{share}, $In{dir});
1018 }
1019
1020 sub restoreFile
1021 {
1022     my($host, $num, $share, $dir, $skipHardLink, $origName) = @_;
1023     my($Privileged) = CheckPermission($host);
1024
1025     #
1026     # Some common content (media) types from www.iana.org (via MIME::Types).
1027     #
1028     my $Ext2ContentType = {
1029         'asc'  => 'text/plain',
1030         'avi'  => 'video/x-msvideo',
1031         'bmp'  => 'image/bmp',
1032         'book' => 'application/x-maker',
1033         'cc'   => 'text/plain',
1034         'cpp'  => 'text/plain',
1035         'csh'  => 'application/x-csh',
1036         'csv'  => 'text/comma-separated-values',
1037         'c'    => 'text/plain',
1038         'deb'  => 'application/x-debian-package',
1039         'doc'  => 'application/msword',
1040         'dot'  => 'application/msword',
1041         'dtd'  => 'text/xml',
1042         'dvi'  => 'application/x-dvi',
1043         'eps'  => 'application/postscript',
1044         'fb'   => 'application/x-maker',
1045         'fbdoc'=> 'application/x-maker',
1046         'fm'   => 'application/x-maker',
1047         'frame'=> 'application/x-maker',
1048         'frm'  => 'application/x-maker',
1049         'gif'  => 'image/gif',
1050         'gtar' => 'application/x-gtar',
1051         'gz'   => 'application/x-gzip',
1052         'hh'   => 'text/plain',
1053         'hpp'  => 'text/plain',
1054         'h'    => 'text/plain',
1055         'html' => 'text/html',
1056         'htmlx'=> 'text/html',
1057         'htm'  => 'text/html',
1058         'iges' => 'model/iges',
1059         'igs'  => 'model/iges',
1060         'jpeg' => 'image/jpeg',
1061         'jpe'  => 'image/jpeg',
1062         'jpg'  => 'image/jpeg',
1063         'js'   => 'application/x-javascript',
1064         'latex'=> 'application/x-latex',
1065         'maker'=> 'application/x-maker',
1066         'mid'  => 'audio/midi',
1067         'midi' => 'audio/midi',
1068         'movie'=> 'video/x-sgi-movie',
1069         'mov'  => 'video/quicktime',
1070         'mp2'  => 'audio/mpeg',
1071         'mp3'  => 'audio/mpeg',
1072         'mpeg' => 'video/mpeg',
1073         'mpg'  => 'video/mpeg',
1074         'mpp'  => 'application/vnd.ms-project',
1075         'pdf'  => 'application/pdf',
1076         'pgp'  => 'application/pgp-signature',
1077         'php'  => 'application/x-httpd-php',
1078         'pht'  => 'application/x-httpd-php',
1079         'phtml'=> 'application/x-httpd-php',
1080         'png'  => 'image/png',
1081         'ppm'  => 'image/x-portable-pixmap',
1082         'ppt'  => 'application/powerpoint',
1083         'ppt'  => 'application/vnd.ms-powerpoint',
1084         'ps'   => 'application/postscript',
1085         'qt'   => 'video/quicktime',
1086         'rgb'  => 'image/x-rgb',
1087         'rtf'  => 'application/rtf',
1088         'rtf'  => 'text/rtf',
1089         'shar' => 'application/x-shar',
1090         'shtml'=> 'text/html',
1091         'swf'  => 'application/x-shockwave-flash',
1092         'tex'  => 'application/x-tex',
1093         'texi' => 'application/x-texinfo',
1094         'texinfo'=> 'application/x-texinfo',
1095         'tgz'  => 'application/x-gtar',
1096         'tiff' => 'image/tiff',
1097         'tif'  => 'image/tiff',
1098         'txt'  => 'text/plain',
1099         'vcf'  => 'text/x-vCard',
1100         'vrml' => 'model/vrml',
1101         'wav'  => 'audio/x-wav',
1102         'wmls' => 'text/vnd.wap.wmlscript',
1103         'wml'  => 'text/vnd.wap.wml',
1104         'wrl'  => 'model/vrml',
1105         'xls'  => 'application/vnd.ms-excel',
1106         'xml'  => 'text/xml',
1107         'xwd'  => 'image/x-xwindowdump',
1108         'z'    => 'application/x-compress',
1109         'zip'  => 'application/zip',
1110         %{$Conf{CgiExt2ContentType}},       # add site-specific values
1111     };
1112     if ( !$Privileged ) {
1113         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_restore_backup_files2}}"));
1114     }
1115     ServerConnect();
1116     ErrorExit($Lang->{Empty_host_name}) if ( $host eq "" );
1117
1118     $dir = "/" if ( $dir eq "" );
1119     my @Backups = $bpc->BackupInfoRead($host);
1120     my $view = BackupPC::View->new($bpc, $host, \@Backups);
1121     my $a = $view->fileAttrib($num, $share, $dir);
1122     if ( $dir =~ m{(^|/)\.\.(/|$)} || !defined($a) ) {
1123         ErrorExit("Can't restore bad file ${EscHTML($dir)}");
1124     }
1125     my $f = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
1126     my $data;
1127     if ( !$skipHardLink && $a->{type} == BPC_FTYPE_HARDLINK ) {
1128         #
1129         # hardlinks should look like the file they point to
1130         #
1131         my $linkName;
1132         while ( $f->read(\$data, 65536) > 0 ) {
1133             $linkName .= $data;
1134         }
1135         $f->close;
1136         $linkName =~ s/^\.\///;
1137         my $share = $1 if ( $dir =~ /^\/?(.*?)\// );
1138         restoreFile($host, $num, $share, $linkName, 1, $dir);
1139         return;
1140     }
1141     $bpc->ServerMesg("log User $User recovered file $host/$num:$share/$dir ($a->{fullPath})");
1142     $dir = $origName if ( defined($origName) );
1143     my $ext = $1 if ( $dir =~ /\.([^\/\.]+)$/ );
1144     my $contentType = $Ext2ContentType->{lc($ext)}
1145                                     || "application/octet-stream";
1146     my $fileName = $1 if ( $dir =~ /.*\/(.*)/ );
1147     $fileName =~ s/"/\\"/g;
1148     print "Content-Type: $contentType\n";
1149     print "Content-Transfer-Encoding: binary\n";
1150     print "Content-Disposition: attachment; filename=\"$fileName\"\n\n";
1151     while ( $f->read(\$data, 1024 * 1024) > 0 ) {
1152         print STDOUT $data;
1153     }
1154     $f->close;
1155 }
1156
1157 sub Action_HostInfo
1158 {
1159     my $host = $1 if ( $In{host} =~ /(.*)/ );
1160     my($statusStr, $startIncrStr);
1161
1162     $host =~ s/^\s+//;
1163     $host =~ s/\s+$//;
1164     return Action_GeneralInfo() if ( $host eq "" );
1165     $host = lc($host)
1166                 if ( !-d "$TopDir/pc/$host" && -d "$TopDir/pc/" . lc($host) );
1167     if ( $host =~ /\.\./ || !-d "$TopDir/pc/$host" ) {
1168         #
1169         # try to lookup by user name
1170         #
1171         if ( !defined($Hosts->{$host}) ) {
1172             foreach my $h ( keys(%$Hosts) ) {
1173                 if ( $Hosts->{$h}{user} eq $host
1174                         || lc($Hosts->{$h}{user}) eq lc($host) ) {
1175                     $host = $h;
1176                     last;
1177                 }
1178             }
1179             CheckPermission();
1180             ErrorExit(eval("qq{$Lang->{Unknown_host_or_user}}"))
1181                                 if ( !defined($Hosts->{$host}) );
1182         }
1183         $In{host} = $host;
1184     }
1185     GetStatusInfo("host(${EscURI($host)})");
1186     $bpc->ConfigRead($host);
1187     %Conf = $bpc->Conf();
1188     my $Privileged = CheckPermission($host);
1189     if ( !$Privileged ) {
1190         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_view_information_about}}"));
1191     }
1192     ReadUserEmailInfo();
1193
1194     my @Backups = $bpc->BackupInfoRead($host);
1195     my($str, $sizeStr, $compStr, $errStr, $warnStr);
1196     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1197         my $startTime = timeStamp2($Backups[$i]{startTime});
1198         my $dur       = $Backups[$i]{endTime} - $Backups[$i]{startTime};
1199         $dur          = 1 if ( $dur <= 0 );
1200         my $duration  = sprintf("%.1f", $dur / 60);
1201         my $MB        = sprintf("%.1f", $Backups[$i]{size} / (1024*1024));
1202         my $MBperSec  = sprintf("%.2f", $Backups[$i]{size} / (1024*1024*$dur));
1203         my $MBExist   = sprintf("%.1f", $Backups[$i]{sizeExist} / (1024*1024));
1204         my $MBNew     = sprintf("%.1f", $Backups[$i]{sizeNew} / (1024*1024));
1205         my($MBExistComp, $ExistComp, $MBNewComp, $NewComp);
1206         if ( $Backups[$i]{sizeExist} && $Backups[$i]{sizeExistComp} ) {
1207             $MBExistComp = sprintf("%.1f", $Backups[$i]{sizeExistComp}
1208                                                 / (1024 * 1024));
1209             $ExistComp = sprintf("%.1f%%", 100 *
1210                   (1 - $Backups[$i]{sizeExistComp} / $Backups[$i]{sizeExist}));
1211         }
1212         if ( $Backups[$i]{sizeNew} && $Backups[$i]{sizeNewComp} ) {
1213             $MBNewComp = sprintf("%.1f", $Backups[$i]{sizeNewComp}
1214                                                 / (1024 * 1024));
1215             $NewComp = sprintf("%.1f%%", 100 *
1216                   (1 - $Backups[$i]{sizeNewComp} / $Backups[$i]{sizeNew}));
1217         }
1218         my $age = sprintf("%.1f", (time - $Backups[$i]{startTime}) / (24*3600));
1219         my $browseURL = "$MyURL?action=browse&host=${EscURI($host)}&num=$Backups[$i]{num}";
1220         my $filled = $Backups[$i]{noFill} ? $Lang->{No} : $Lang->{Yes};
1221         $filled .= " ($Backups[$i]{fillFromNum}) "
1222                             if ( $Backups[$i]{fillFromNum} ne "" );
1223         my $ltype;
1224         if ($Backups[$i]{type} eq "full") { $ltype = $Lang->{full}; }
1225         else { $ltype = $Lang->{incremental}; }
1226         $str .= <<EOF;
1227 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1228     <td align="center"> $ltype </td>
1229     <td align="center"> $filled </td>
1230     <td align="right">  $startTime </td>
1231     <td align="right">  $duration </td>
1232     <td align="right">  $age </td>
1233     <td align="left">   <tt>$TopDir/pc/$host/$Backups[$i]{num}</tt> </td></tr>
1234 EOF
1235         $sizeStr .= <<EOF;
1236 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1237     <td align="center"> $ltype </td>
1238     <td align="right">  $Backups[$i]{nFiles} </td>
1239     <td align="right">  $MB </td>
1240     <td align="right">  $MBperSec </td>
1241     <td align="right">  $Backups[$i]{nFilesExist} </td>
1242     <td align="right">  $MBExist </td>
1243     <td align="right">  $Backups[$i]{nFilesNew} </td>
1244     <td align="right">  $MBNew </td>
1245 </tr>
1246 EOF
1247         my $is_compress = $Backups[$i]{compress} || $Lang->{off};
1248         if (! $ExistComp) { $ExistComp = "&nbsp;"; }
1249         if (! $MBExistComp) { $MBExistComp = "&nbsp;"; }
1250         $compStr .= <<EOF;
1251 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1252     <td align="center"> $ltype </td>
1253     <td align="center"> $is_compress </td> 
1254     <td align="right">  $MBExist </td>
1255     <td align="right">  $MBExistComp </td> 
1256     <td align="right">  $ExistComp </td>   
1257     <td align="right">  $MBNew </td>
1258     <td align="right">  $MBNewComp </td>
1259     <td align="right">  $NewComp </td>
1260 </tr>
1261 EOF
1262         $errStr .= <<EOF;
1263 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1264     <td align="center"> $ltype </td>
1265     <td align="center"> <a href="$MyURL?action=view&type=XferLOG&num=$Backups[$i]{num}&host=${EscURI($host)}">XferLOG</a>,
1266                       <a href="$MyURL?action=view&type=XferErr&num=$Backups[$i]{num}&host=${EscURI($host)}">Errors</a> </td>
1267     <td align="right">  $Backups[$i]{xferErrs} </td>
1268     <td align="right">  $Backups[$i]{xferBadFile} </td>
1269     <td align="right">  $Backups[$i]{xferBadShare} </td>
1270     <td align="right">  $Backups[$i]{tarErrs} </td></tr>
1271 EOF
1272     }
1273
1274     my @Restores = $bpc->RestoreInfoRead($host);
1275     my $restoreStr;
1276
1277     for ( my $i = 0 ; $i < @Restores ; $i++ ) {
1278         my $startTime = timeStamp2($Restores[$i]{startTime});
1279         my $dur       = $Restores[$i]{endTime} - $Restores[$i]{startTime};
1280         $dur          = 1 if ( $dur <= 0 );
1281         my $duration  = sprintf("%.1f", $dur / 60);
1282         my $MB        = sprintf("%.1f", $Restores[$i]{size} / (1024*1024));
1283         my $MBperSec  = sprintf("%.2f", $Restores[$i]{size} / (1024*1024*$dur));
1284         my $Restores_Result = $Lang->{failed};
1285         if ($Restores[$i]{result} ne "failed") { $Restores_Result = $Lang->{success}; }
1286         $restoreStr  .= <<EOF;
1287 <tr><td align="center"><a href="$MyURL?action=restoreInfo&num=$Restores[$i]{num}&host=${EscURI($host)}">$Restores[$i]{num}</a> </td>
1288     <td align="center"> $Restores_Result </td>
1289     <td align="right"> $startTime </td>
1290     <td align="right"> $duration </td>
1291     <td align="right"> $Restores[$i]{nFiles} </td>
1292     <td align="right"> $MB </td>
1293     <td align="right"> $Restores[$i]{tarCreateErrs} </td>
1294     <td align="right"> $Restores[$i]{xferErrs} </td>
1295 </tr>
1296 EOF
1297     }
1298     if ( $restoreStr ne "" ) {
1299         $restoreStr = eval("qq{$Lang->{Restore_Summary}}");
1300     }
1301     if ( @Backups == 0 ) {
1302         $warnStr = $Lang->{This_PC_has_never_been_backed_up};
1303     }
1304     if ( defined($Hosts->{$host}) ) {
1305         my $user = $Hosts->{$host}{user};
1306         my @moreUsers = sort(keys(%{$Hosts->{$host}{moreUsers}}));
1307         my $moreUserStr;
1308         foreach my $u ( sort(keys(%{$Hosts->{$host}{moreUsers}})) ) {
1309             $moreUserStr .= ", " if ( $moreUserStr ne "" );
1310             $moreUserStr .= "${UserLink($u)}";
1311         }
1312         if ( $moreUserStr ne "" ) {
1313             $moreUserStr = " ($Lang->{and} $moreUserStr).\n";
1314         } else {
1315             $moreUserStr = ".\n";
1316         }
1317         if ( $user ne "" ) {
1318             $statusStr .= eval("qq{$Lang->{This_PC_is_used_by}$moreUserStr}");
1319         }
1320         if ( defined($UserEmailInfo{$user})
1321                 && $UserEmailInfo{$user}{lastHost} eq $host ) {
1322             my $mailTime = timeStamp2($UserEmailInfo{$user}{lastTime});
1323             my $subj     = $UserEmailInfo{$user}{lastSubj};
1324             $statusStr  .= eval("qq{$Lang->{Last_email_sent_to__was_at___subject}}");
1325         }
1326     }
1327     if ( defined($Jobs{$host}) ) {
1328         my $startTime = timeStamp2($Jobs{$host}{startTime});
1329         (my $cmd = $Jobs{$host}{cmd}) =~ s/$BinDir\///g;
1330         $statusStr .= eval("qq{$Lang->{The_command_cmd_is_currently_running_for_started}}");
1331     }
1332     if ( $StatusHost{BgQueueOn} ) {
1333         $statusStr .= eval("qq{$Lang->{Host_host_is_queued_on_the_background_queue_will_be_backed_up_soon}}");
1334     }
1335     if ( $StatusHost{UserQueueOn} ) {
1336         $statusStr .= eval("qq{$Lang->{Host_host_is_queued_on_the_user_queue__will_be_backed_up_soon}}");
1337     }
1338     if ( $StatusHost{CmdQueueOn} ) {
1339         $statusStr .= eval("qq{$Lang->{A_command_for_host_is_on_the_command_queue_will_run_soon}}");
1340     }
1341     my $startTime = timeStamp2($StatusHost{endTime} == 0 ?
1342                 $StatusHost{startTime} : $StatusHost{endTime});
1343     my $reason = "";
1344     if ( $StatusHost{reason} ne "" ) {
1345         $reason = " ($Lang->{$StatusHost{reason}})";
1346     }
1347     $statusStr .= eval("qq{$Lang->{Last_status_is_state_StatusHost_state_reason_as_of_startTime}}");
1348
1349     if ( $StatusHost{error} ne "" ) {
1350         $statusStr .= eval("qq{$Lang->{Last_error_is____EscHTML_StatusHost_error}}");
1351     }
1352     my $priorStr = "Pings";
1353     if ( $StatusHost{deadCnt} > 0 ) {
1354         $statusStr .= eval("qq{$Lang->{Pings_to_host_have_failed_StatusHost_deadCnt__consecutive_times}}");
1355         $priorStr = $Lang->{Prior_to_that__pings};
1356     }
1357     if ( $StatusHost{aliveCnt} > 0 ) {
1358         $statusStr .= eval("qq{$Lang->{priorStr_to_host_have_succeeded_StatusHostaliveCnt_consecutive_times}}");
1359
1360         if ( $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt}
1361                 && $Conf{BlackoutGoodCnt} >= 0 && $Conf{BlackoutHourBegin} >= 0
1362                 && $Conf{BlackoutHourEnd} >= 0 ) {
1363             my(@days) = qw(Sun Mon Tue Wed Thu Fri Sat);
1364             my($days) = join(", ", @days[@{$Conf{BlackoutWeekDays}}]);
1365             my($t0) = sprintf("%d:%02d", $Conf{BlackoutHourBegin},
1366                             60 * ($Conf{BlackoutHourBegin}
1367                                      - int($Conf{BlackoutHourBegin})));
1368             my($t1) = sprintf("%d:%02d", $Conf{BlackoutHourEnd},
1369                             60 * ($Conf{BlackoutHourEnd}
1370                                      - int($Conf{BlackoutHourEnd})));
1371             $statusStr .= eval("qq{$Lang->{Because__host_has_been_on_the_network_at_least__Conf_BlackoutGoodCnt_consecutive_times___}}");
1372         }
1373     }
1374     if ( $StatusHost{backoffTime} > time ) {
1375         my $hours = sprintf("%.1f", ($StatusHost{backoffTime} - time) / 3600);
1376         $statusStr .= eval("qq{$Lang->{Backups_are_deferred_for_hours_hours_change_this_number}}");
1377
1378     }
1379     if ( @Backups ) {
1380         # only allow incremental if there are already some backups
1381         $startIncrStr = <<EOF;
1382 <input type="submit" value="\$Lang->{Start_Incr_Backup}" name="action">
1383 EOF
1384     }
1385
1386     $startIncrStr = eval ("qq{$startIncrStr}");
1387
1388     Header(eval("qq{$Lang->{Host__host_Backup_Summary}}"));
1389     print(eval("qq{$Lang->{Host__host_Backup_Summary2}}"));
1390     Trailer();
1391 }
1392
1393 sub Action_GeneralInfo
1394 {
1395     GetStatusInfo("info jobs hosts queueLen");
1396     my $Privileged = CheckPermission();
1397
1398     my($jobStr, $statusStr, $tarPidHdr);
1399     foreach my $host ( sort(keys(%Jobs)) ) {
1400         my $startTime = timeStamp2($Jobs{$host}{startTime});
1401         next if ( $host eq $bpc->trashJob
1402                     && $Jobs{$host}{processState} ne "running" );
1403         $Jobs{$host}{type} = $Status{$host}{type}
1404                     if ( $Jobs{$host}{type} eq "" && defined($Status{$host}));
1405         (my $cmd = $Jobs{$host}{cmd}) =~ s/$BinDir\///g;
1406         $jobStr .= <<EOF;
1407 <tr><td> ${HostLink($host)} </td>
1408     <td align="center"> $Jobs{$host}{type} </td>
1409     <td align="center"> ${UserLink($Hosts->{$host}{user})} </td>
1410     <td> $startTime </td>
1411     <td> $cmd </td>
1412     <td align="center"> $Jobs{$host}{pid} </td>
1413     <td align="center"> $Jobs{$host}{xferPid} </td>
1414 EOF
1415         if ( $Jobs{$host}{tarPid} > 0 ) {
1416             $jobStr .= "    <td align=\"center\"> $Jobs{$host}{tarPid} </td>\n";
1417             $tarPidHdr ||= "<td align=\"center\"> tar PID </td>\n";
1418         }
1419         $jobStr .= "</tr>\n";
1420     }
1421     foreach my $host ( sort(keys(%Status)) ) {
1422         next if ( $Status{$host}{reason} ne "Reason_backup_failed"
1423                || $Status{$host}{error} =~ /^Can't find host \Q$host/ );
1424         my $startTime = timeStamp2($Status{$host}{startTime});
1425         my($errorTime, $XferViewStr);
1426         if ( $Status{$host}{errorTime} > 0 ) {
1427             $errorTime = timeStamp2($Status{$host}{errorTime});
1428         }
1429         if ( -f "$TopDir/pc/$host/SmbLOG.bad"
1430                 || -f "$TopDir/pc/$host/SmbLOG.bad.z"
1431                 || -f "$TopDir/pc/$host/XferLOG.bad"
1432                 || -f "$TopDir/pc/$host/XferLOG.bad.z"
1433                 ) {
1434             $XferViewStr = <<EOF;
1435 <a href="$MyURL?action=view&type=XferLOGbad&host=${EscURI($host)}">XferLOG</a>,
1436 <a href="$MyURL?action=view&type=XferErrbad&host=${EscURI($host)}">XferErr</a>
1437 EOF
1438         } else {
1439             $XferViewStr = "";
1440         }
1441         (my $shortErr = $Status{$host}{error}) =~ s/(.{48}).*/$1.../;   
1442         $statusStr .= <<EOF;
1443 <tr><td> ${HostLink($host)} </td>
1444     <td align="center"> $Status{$host}{type} </td>
1445     <td align="center"> ${UserLink($Hosts->{$host}{user})} </td>
1446     <td align="right"> $startTime </td>
1447     <td> $XferViewStr </td>
1448     <td align="right"> $errorTime </td>
1449     <td> ${EscHTML($shortErr)} </td></tr>
1450 EOF
1451     }
1452     my $now          = timeStamp2(time);
1453     my $nextWakeupTime = timeStamp2($Info{nextWakeup});
1454     my $DUlastTime   = timeStamp2($Info{DUlastValueTime});
1455     my $DUmaxTime    = timeStamp2($Info{DUDailyMaxTime});
1456     my $numBgQueue   = $QueueLen{BgQueue};
1457     my $numUserQueue = $QueueLen{UserQueue};
1458     my $numCmdQueue  = $QueueLen{CmdQueue};
1459     my $serverStartTime = timeStamp2($Info{startTime});
1460     my $poolInfo     = genPoolInfo("pool", \%Info);
1461     my $cpoolInfo    = genPoolInfo("cpool", \%Info);
1462     if ( $Info{poolFileCnt} > 0 && $Info{cpoolFileCnt} > 0 ) {
1463         $poolInfo = <<EOF;
1464 <li>Uncompressed pool:
1465 <ul>
1466 $poolInfo
1467 </ul>
1468 <li>Compressed pool:
1469 <ul>
1470 $cpoolInfo
1471 </ul>
1472 EOF
1473     } elsif ( $Info{cpoolFileCnt} > 0 ) {
1474         $poolInfo = $cpoolInfo;
1475     }
1476
1477     Header($Lang->{H_BackupPC_Server_Status});
1478     print (eval ("qq{$Lang->{BackupPC_Server_Status}}"));
1479     Trailer();
1480 }
1481
1482 sub Action_RestoreInfo
1483 {
1484     my $Privileged = CheckPermission($In{host});
1485     my $host = $1 if ( $In{host} =~ /(.*)/ );
1486     my $num  = $In{num};
1487     my $i;
1488
1489     if ( !$Privileged ) {
1490         ErrorExit($Lang->{Only_privileged_users_can_view_restore_information});
1491     }
1492     #
1493     # Find the requested restore
1494     #
1495     my @Restores = $bpc->RestoreInfoRead($host);
1496     for ( $i = 0 ; $i < @Restores ; $i++ ) {
1497         last if ( $Restores[$i]{num} == $num );
1498     }
1499     if ( $i >= @Restores ) {
1500         ErrorExit(eval("qq{$Lang->{Restore_number__num_for_host__does_not_exist}}"));
1501     }
1502
1503     %RestoreReq = ();
1504     do "$TopDir/pc/$host/RestoreInfo.$Restores[$i]{num}"
1505             if ( -f "$TopDir/pc/$host/RestoreInfo.$Restores[$i]{num}" );
1506
1507     my $startTime = timeStamp2($Restores[$i]{startTime});
1508     my $reqTime   = timeStamp2($RestoreReq{reqTime});
1509     my $dur       = $Restores[$i]{endTime} - $Restores[$i]{startTime};
1510     $dur          = 1 if ( $dur <= 0 );
1511     my $duration  = sprintf("%.1f", $dur / 60);
1512     my $MB        = sprintf("%.1f", $Restores[$i]{size} / (1024*1024));
1513     my $MBperSec  = sprintf("%.2f", $Restores[$i]{size} / (1024*1024*$dur));
1514
1515     my $fileListStr = "";
1516     foreach my $f ( @{$RestoreReq{fileList}} ) {
1517         my $targetFile = $f;
1518         (my $strippedShareSrc  = $RestoreReq{shareSrc}) =~ s/^\///;
1519         (my $strippedShareDest = $RestoreReq{shareDest}) =~ s/^\///;
1520         substr($targetFile, 0, length($RestoreReq{pathHdrSrc}))
1521                                         = $RestoreReq{pathHdrDest};
1522         $fileListStr .= <<EOF;
1523 <tr><td>$RestoreReq{hostSrc}:/$strippedShareSrc$f</td><td>$RestoreReq{hostDest}:/$strippedShareDest$targetFile</td></tr>
1524 EOF
1525     }
1526
1527     Header(eval("qq{$Lang->{Restore___num_details_for__host}}"));
1528     print(eval("qq{$Lang->{Restore___num_details_for__host2 }}"));
1529     Trailer();
1530 }
1531     
1532 ###########################################################################
1533 # Miscellaneous subroutines
1534 ###########################################################################
1535
1536 sub timeStamp2
1537 {
1538     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
1539               = localtime($_[0] == 0 ? time : $_[0] );
1540     $year += 1900;
1541     $mon++;
1542     if ( $Conf{CgiDateFormatMMDD} ) {
1543         return sprintf("$mon/$mday %02d:%02d", $hour, $min);
1544     } else {
1545         return sprintf("$mday/$mon %02d:%02d", $hour, $min);
1546     }
1547 }
1548
1549 sub HostLink
1550 {
1551     my($host) = @_;
1552     my($s);
1553     if ( defined($Hosts->{$host}) || defined($Status{$host}) ) {
1554         $s = "<a href=\"$MyURL?host=${EscURI($host)}\">$host</a>";
1555     } else {
1556         $s = $host;
1557     }
1558     return \$s;
1559 }
1560
1561 sub UserLink
1562 {
1563     my($user) = @_;
1564     my($s);
1565
1566     return \$user if ( $user eq ""
1567                     || $Conf{CgiUserUrlCreate} eq "" );
1568     if ( $Conf{CgiUserHomePageCheck} eq ""
1569             || -f sprintf($Conf{CgiUserHomePageCheck}, $user, $user, $user) ) {
1570         $s = "<a href=\""
1571              . sprintf($Conf{CgiUserUrlCreate}, $user, $user, $user)
1572              . "\">$user</a>";
1573     } else {
1574         $s = $user;
1575     }
1576     return \$s;
1577 }
1578
1579 sub EscHTML
1580 {
1581     my($s) = @_;
1582     $s =~ s/&/&amp;/g;
1583     $s =~ s/\"/&quot;/g;
1584     $s =~ s/>/&gt;/g;
1585     $s =~ s/</&lt;/g;
1586     $s =~ s{([^[:print:]])}{sprintf("&\#x%02X;", ord($1));}eg;
1587     return \$s;
1588 }
1589
1590 sub EscURI
1591 {
1592     my($s) = @_;
1593     $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1594     return \$s;
1595 }
1596
1597 sub ErrorExit
1598 {
1599     my(@mesg) = @_;
1600     my($head) = shift(@mesg);
1601     my($mesg) = join("</p>\n<p>", @mesg);
1602     $Conf{CgiHeaderFontType} ||= "arial"; 
1603     $Conf{CgiHeaderFontSize} ||= "3";  
1604     $Conf{CgiNavBarBgColor}  ||= "#ddeeee";
1605     $Conf{CgiHeaderBgColor}  ||= "#99cc33";
1606
1607     $bpc->ServerMesg("log User $User (host=$In{host}) got CGI error: $head")
1608                             if ( defined($bpc) );
1609     if ( !defined($Lang->{Error}) ) {
1610         Header("BackupPC: Error");
1611         $mesg = <<EOF if ( !defined($mesg) );
1612 There is some problem with the BackupPC installation.
1613 Please check the permissions on BackupPC_Admin.
1614 EOF
1615         print <<EOF;
1616 ${h1("Error: Unable to read config.pl or language strings!!")}
1617 <p>$mesg</p>
1618 EOF
1619         Trailer();
1620     } else {
1621         Header(eval("qq{$Lang->{Error}}"));
1622         print (eval("qq{$Lang->{Error____head}}"));
1623         Trailer();
1624     }
1625     exit(1);
1626 }
1627
1628 sub ServerConnect
1629 {
1630     #
1631     # Verify that the server connection is ok
1632     #
1633     return if ( $bpc->ServerOK() );
1634     $bpc->ServerDisconnect();
1635     if ( my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort}) ) {
1636         ErrorExit(eval("qq{$Lang->{Unable_to_connect_to_BackupPC_server}}"));
1637     }
1638 }
1639
1640 sub GetStatusInfo
1641 {
1642     my($status) = @_;
1643     ServerConnect();
1644     my $reply = $bpc->ServerMesg("status $status");
1645     $reply = $1 if ( $reply =~ /(.*)/s );
1646     eval($reply);
1647     # ignore status related to admin and trashClean jobs
1648     if ( $status =~ /\bhosts\b/ ) {
1649         delete($Status{$bpc->adminJob});
1650         delete($Status{$bpc->trashJob});
1651     }
1652 }
1653
1654 sub ReadUserEmailInfo
1655 {
1656     if ( (stat("$TopDir/log/UserEmailInfo.pl"))[9] != $UserEmailInfoMTime ) {
1657         do "$TopDir/log/UserEmailInfo.pl";
1658         $UserEmailInfoMTime = (stat("$TopDir/log/UserEmailInfo.pl"))[9];
1659     }
1660 }
1661
1662 #
1663 # Check if the user is privileged.  A privileged user can access
1664 # any information (backup files, logs, status pages etc).
1665 #
1666 # A user is privileged if they belong to the group
1667 # $Conf{CgiAdminUserGroup}, or they are in $Conf{CgiAdminUsers}
1668 # or they are the user assigned to a host in the host file.
1669 #
1670 sub CheckPermission
1671 {
1672     my($host) = @_;
1673     my $Privileged = 0;
1674
1675     return 0 if ( $User eq "" || ($host ne "" && !defined($Hosts->{$host})) );
1676     if ( $Conf{CgiAdminUserGroup} ne "" ) {
1677         my($n,$p,$gid,$mem) = getgrnam($Conf{CgiAdminUserGroup});
1678         $Privileged ||= ($mem =~ /\b$User\b/);
1679     }
1680     if ( $Conf{CgiAdminUsers} ne "" ) {
1681         $Privileged ||= ($Conf{CgiAdminUsers} =~ /\b$User\b/);
1682         $Privileged ||= $Conf{CgiAdminUsers} eq "*";
1683     }
1684     $PrivAdmin = $Privileged;
1685     $Privileged ||= $User eq $Hosts->{$host}{user};
1686     $Privileged ||= defined($Hosts->{$host}{operators}{$User});
1687
1688     return $Privileged;
1689 }
1690
1691 #
1692 # Returns the list of hosts that should appear in the navigation bar
1693 # for this user.  If $Conf{CgiNavBarAdminAllHosts} is set, the admin
1694 # gets all the hosts.  Otherwise, regular users get hosts for which
1695 # they are the user or are listed in the moreUsers column in the
1696 # hosts file.
1697 #
1698 sub GetUserHosts
1699 {
1700     if ( $Conf{CgiNavBarAdminAllHosts} && CheckPermission() ) {
1701        return sort keys %$Hosts;
1702     }
1703
1704     return sort grep { $Hosts->{$_}{user} eq $User ||
1705                        defined($Hosts->{$_}{moreUsers}{$User}) } keys(%$Hosts);
1706 }
1707
1708 #
1709 # Given a host name tries to find the IP address.  For non-dhcp hosts
1710 # we just return the host name.  For dhcp hosts we check the address
1711 # the user is using ($ENV{REMOTE_ADDR}) and also the last-known IP
1712 # address for $host.  (Later we should replace this with a broadcast
1713 # nmblookup.)
1714 #
1715 sub ConfirmIPAddress
1716 {
1717     my($host) = @_;
1718     my $ipAddr = $host;
1719
1720     if ( $Hosts->{$host}{dhcp}
1721                && $ENV{REMOTE_ADDR} =~ /^(\d+[\.\d]*)$/ ) {
1722         $ipAddr = $1;
1723         my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($ipAddr);
1724         if ( $netBiosHost ne $host ) {
1725             my($tryIP);
1726             GetStatusInfo("host(${EscURI($host)})");
1727             if ( defined($StatusHost{dhcpHostIP})
1728                         && $StatusHost{dhcpHostIP} ne $ipAddr ) {
1729                 $tryIP = eval("qq{$Lang->{tryIP}}");
1730                 ($netBiosHost, $netBiosUser)
1731                         = $bpc->NetBiosInfoGet($StatusHost{dhcpHostIP});
1732             }
1733             if ( $netBiosHost ne $host ) {
1734                 ErrorExit(eval("qq{$Lang->{Can_t_find_IP_address_for}}"),
1735                           eval("qq{$Lang->{host_is_a_DHCP_host}}"));
1736             }
1737             $ipAddr = $StatusHost{dhcpHostIP};
1738         }
1739     }
1740     return $ipAddr;
1741 }
1742
1743 sub genPoolInfo
1744 {
1745     my($name, $info) = @_;
1746     my $poolSize   = sprintf("%.2f", $info->{"${name}Kb"} / (1000 * 1024));
1747     my $poolRmSize = sprintf("%.2f", $info->{"${name}KbRm"} / (1000 * 1024));
1748     my $poolTime   = timeStamp2($info->{"${name}Time"});
1749     $info->{"${name}FileCntRm"} = $info->{"${name}FileCntRm"} + 0;
1750     return eval("qq{$Lang->{Pool_Stat}}");
1751 }
1752
1753 ###########################################################################
1754 # HTML layout subroutines
1755 ###########################################################################
1756
1757 sub Header
1758 {
1759     my($title) = @_;
1760     my @adminLinks = (
1761         { link => "",                          name => $Lang->{Status},
1762                                                priv => 1},
1763         { link => "?action=summary",           name => $Lang->{PC_Summary} },
1764         { link => "?action=view&type=LOG",     name => $Lang->{LOG_file} },
1765         { link => "?action=LOGlist",           name => $Lang->{Old_LOGs} },
1766         { link => "?action=emailSummary",      name => $Lang->{Email_summary} },
1767         { link => "?action=view&type=config",  name => $Lang->{Config_file} },
1768         { link => "?action=view&type=hosts",   name => $Lang->{Hosts_file} },
1769         { link => "?action=queue",             name => $Lang->{Current_queues} },
1770         { link => "?action=view&type=docs",    name => $Lang->{Documentation},
1771                                                priv => 1},
1772         { link => "http://backuppc.sourceforge.net/faq", name => "FAQ",
1773                                                priv => 1},
1774         { link => "http://backuppc.sourceforge.net", name => "SourceForge",
1775                                                priv => 1},
1776     );
1777     print $Cgi->header();
1778     print <<EOF;
1779 <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
1780 <html><head>
1781 <title>$title</title>
1782 $Conf{CgiHeaders}
1783 </head><body bgcolor="$Conf{CgiBodyBgColor}">
1784 <table cellpadding="0" cellspacing="0" border="0">
1785 <tr valign="top"><td valign="top" bgcolor="$Conf{CgiNavBarBgColor}" width="10%">
1786 EOF
1787     NavSectionTitle("BackupPC");
1788     print "&nbsp;\n";
1789     if ( defined($In{host}) && defined($Hosts->{$In{host}}) ) {
1790         my $host = $In{host};
1791         NavSectionTitle( eval("qq{$Lang->{Host_Inhost}}") );
1792         NavSectionStart();
1793         NavLink("?host=${EscURI($host)}", $Lang->{Home});
1794         NavLink("?action=view&type=LOG&host=${EscURI($host)}", $Lang->{LOG_file});
1795         NavLink("?action=LOGlist&host=${EscURI($host)}", $Lang->{Old_LOGs});
1796         if ( -f "$TopDir/pc/$host/SmbLOG.bad"
1797                     || -f "$TopDir/pc/$host/SmbLOG.bad.z"
1798                     || -f "$TopDir/pc/$host/XferLOG.bad"
1799                     || -f "$TopDir/pc/$host/XferLOG.bad.z" ) {
1800             NavLink("?action=view&type=XferLOGbad&host=${EscURI($host)}",
1801                                 $Lang->{Last_bad_XferLOG});
1802             NavLink("?action=view&type=XferErrbad&host=${EscURI($host)}",
1803                                 $Lang->{Last_bad_XferLOG_errors_only});
1804         }
1805         if ( -f "$TopDir/pc/$host/config.pl" ) {
1806             NavLink("?action=view&type=config&host=${EscURI($host)}", $Lang->{Config_file});
1807         }
1808         NavSectionEnd();
1809     }
1810     NavSectionTitle($Lang->{Hosts});
1811     if ( defined($Hosts) && %$Hosts > 0 ) {
1812         NavSectionStart(0);
1813         foreach my $host ( GetUserHosts() ) {
1814             NavLink("?host=${EscURI($host)}", $host);
1815         }
1816         NavSectionEnd();
1817     }
1818     print <<EOF;
1819 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1820     <tr><td>$Lang->{Host_or_User_name}</td>
1821     <tr><td><form action="$MyURL" method="get"><small>
1822     <input type="text" name="host" size="10" maxlength="64">
1823     <input type="hidden" name="action" value="hostInfo"><input type="submit" value="$Lang->{Go}" name="ignore">
1824     </small></form></td></tr>
1825 </table>
1826 EOF
1827     NavSectionTitle($Lang->{NavSectionTitle_});
1828     NavSectionStart();
1829     foreach my $l ( @adminLinks ) {
1830         if ( $PrivAdmin || $l->{priv} ) {
1831             NavLink($l->{link}, $l->{name});
1832         } else {
1833             NavLink(undef, $l->{name});
1834         }
1835     }
1836     NavSectionEnd();
1837     print <<EOF;
1838 </td><td valign="top" width="5">&nbsp;&nbsp;</td>
1839 <td valign="top" width="90%">
1840 EOF
1841 }
1842
1843 sub Trailer
1844 {
1845     print <<EOF;
1846 </td></table>
1847 </body></html>
1848 EOF
1849 }
1850
1851
1852 sub NavSectionTitle
1853 {
1854     my($head) = @_;
1855     print <<EOF;
1856 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1857 <tr><td bgcolor="$Conf{CgiHeaderBgColor}"><font face="$Conf{CgiHeaderFontType}"
1858 size="$Conf{CgiHeaderFontSize}"><b>$head</b>
1859 </font></td></tr>
1860 </table>
1861 EOF
1862 }
1863
1864 sub NavSectionStart
1865 {
1866     my($padding) = @_;
1867
1868     $padding = 2 if ( !defined($padding) );
1869     print <<EOF;
1870 <table cellpadding="$padding" cellspacing="0" border="0" width="100%">
1871 EOF
1872 }
1873
1874 sub NavSectionEnd
1875 {
1876     print "</table>\n";
1877 }
1878
1879 sub NavLink
1880 {
1881     my($link, $text) = @_;
1882     print "<tr><td width=\"2%\" valign=\"top\"><b>&middot;</b></td>";
1883     if ( defined($link) ) {
1884         $link = "$MyURL$link" if ( $link eq "" || $link =~ /^\?/ );
1885         print <<EOF;
1886 <td width="98%"><a href="$link"><small>$text</small></a></td></tr>
1887 EOF
1888     } else {
1889         print <<EOF;
1890 <td width="98%"><small>$text</small></td></tr>
1891 EOF
1892     }
1893 }
1894
1895 sub h1
1896 {
1897     my($str) = @_;
1898     return \<<EOF;
1899 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1900 <tr>
1901 <td bgcolor="$Conf{CgiHeaderBgColor}">&nbsp;<font face="$Conf{CgiHeaderFontType}"
1902     size="$Conf{CgiHeaderFontSize}"><b>$str</b></font>
1903 </td></tr>
1904 </table>
1905 EOF
1906 }
1907
1908 sub h2
1909 {
1910     my($str) = @_;
1911     return \<<EOF;
1912 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1913 <tr>
1914 <td bgcolor="$Conf{CgiHeaderBgColor}">&nbsp;<font face="$Conf{CgiHeaderFontType}"
1915     size="$Conf{CgiHeaderFontSize}"><b>$str</b></font>
1916 </td></tr>
1917 </table>
1918 EOF
1919 }