- added $Conf{ClientNameAlias}, which allows the host name to be
[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.0_CVS, released 18 Jan 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     my $relDir  = $dir;
583     my $currDir = undef;
584
585     #
586     # Loop up the directory tree until we hit the top.
587     #
588     my(@DirStrPrev);
589     while ( 1 ) {
590         my($fLast, $fLastum, @DirStr);
591
592         $attr = $view->dirAttrib($num, $share, $relDir);
593         if ( !defined($attr) ) {
594             ErrorExit(eval("qq{$Lang->{Can_t_browse_bad_directory_name2}}"));
595         }
596
597         my $fileCnt = 0;          # file counter
598         $fLast = $dirStr = "";
599
600         #
601         # Loop over each of the files in this directory
602         #
603         foreach my $f ( sort(keys(%$attr)) ) {
604             my($dirOpen, $gotDir, $imgStr, $img);
605             my $fURI = $f;                             # URI escaped $f
606             my $shareURI = $share;                     # URI escaped $share
607             (my $path = "$relDir/$f") =~ s{//+}{/}g;
608             if ( $shareURI eq "" ) {
609                 $shareURI = $path;
610                 $path  = "/";
611             }
612             $path =~ s{^/+}{/};
613             $path     =~ s/([^\w.\/-])/uc sprintf("%%%02X", ord($1))/eg;
614             $fURI     =~ s/([^\w.\/-])/uc sprintf("%%%02X", ord($1))/eg;
615             $shareURI =~ s/([^\w.\/-])/uc sprintf("%%%02X", ord($1))/eg;
616             $dirOpen  = 1 if ( defined($currDir) && $f eq $currDir );
617             if ( $attr->{$f}{type} == BPC_FTYPE_DIR ) {
618                 #
619                 # Display directory if it exists in current backup.
620                 # First find out if there are subdirs
621                 #
622                 my($bold, $unbold, $BGcolor);
623                 $img |= 1 << 6;
624                 $img |= 1 << 5 if ( $attr->{$f}{nlink} > 2 );
625                 if ( $dirOpen ) {
626                     $bold = "<b>";
627                     $unbold = "</b>";
628                     $img |= 1 << 2;
629                     $img |= 1 << 3 if ( $attr->{$f}{nlink} > 2 );
630                 }
631                 my $imgFileName = sprintf("%07b.gif", $img);
632                 $imgStr = "<img src=\"$Conf{CgiImageDirURL}/$imgFileName\" align=\"absmiddle\" width=\"9\" height=\"19\" border=\"0\">";
633                 if ( "$relDir/$f" eq $dir ) {
634                     $BGcolor = " bgcolor=\"$Conf{CgiHeaderBgColor}\"";
635                 } else {
636                     $BGcolor = "";
637                 }
638                 my $dirName = $f;
639                 $dirName =~ s/ /&nbsp;/g;
640                 push(@DirStr, {needTick => 1,
641                                tdArgs   => $BGcolor,
642                                link     => <<EOF});
643 <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>
644 EOF
645                 $fileCnt++;
646                 $gotDir = 1;
647                 if ( $dirOpen ) {
648                     my($lastTick, $doneLastTick);
649                     foreach my $d ( @DirStrPrev ) {
650                         $lastTick = $d if ( $d->{needTick} );
651                     }
652                     $doneLastTick = 1 if ( !defined($lastTick) );
653                     foreach my $d ( @DirStrPrev ) {
654                         $img = 0;
655                         if  ( $d->{needTick} ) {
656                             $img |= 1 << 0;
657                         }
658                         if ( $d == $lastTick ) {
659                             $img |= 1 << 4;
660                             $doneLastTick = 1;
661                         } elsif ( !$doneLastTick ) {
662                             $img |= 1 << 3 | 1 << 4;
663                         }
664                         my $imgFileName = sprintf("%07b.gif", $img);
665                         $imgStr = "<img src=\"$Conf{CgiImageDirURL}/$imgFileName\" align=\"absmiddle\" width=\"9\" height=\"19\" border=\"0\">";
666                         push(@DirStr, {needTick => 0,
667                                        tdArgs   => $d->{tdArgs},
668                                        link     => $imgStr . $d->{link}
669                         });
670                     }
671                 }
672             }
673             if ( $relDir eq $dir ) {
674                 #
675                 # This is the selected directory, so display all the files
676                 #
677                 my $attrStr;
678                 if ( defined($a = $attr->{$f}) ) {
679                     my $mtimeStr = $bpc->timeStamp($a->{mtime});
680                     # UGH -> fix this
681                     my $typeStr  = BackupPC::Attrib::fileType2Text(undef,
682                                                                    $a->{type});
683                     my $modeStr  = sprintf("0%o", $a->{mode} & 07777);
684                     $attrStr .= <<EOF;
685     <td align="center">$typeStr</td>
686     <td align="center">$modeStr</td>
687     <td align="center">$a->{backupNum}</td>
688     <td align="right">$a->{size}</td>
689     <td align="right">$mtimeStr</td>
690 </tr>
691 EOF
692                 } else {
693                     $attrStr .= "<td colspan=\"5\" align=\"center\"> </td>\n";
694                 }
695                 (my $fDisp = "${EscHTML($f)}") =~ s/ /&nbsp;/g;
696                 if ( $gotDir ) {
697                     $fileStr .= <<EOF;
698 <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>
699 $attrStr
700 </tr>
701 EOF
702                 } else {
703                     $fileStr .= <<EOF;
704 <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>
705 $attrStr
706 </tr>
707 EOF
708                 }
709                 $checkBoxCnt++;
710             }
711         }
712         @DirStrPrev = @DirStr;
713         last if ( $relDir eq "" && $share eq "" );
714         # 
715         # Prune the last directory off $relDir, or at the very end
716         # do the top-level directory.
717         #
718         if ( $relDir eq "" || $relDir eq "/" ) {
719             $currDir = $share;
720             $share = "";
721             $relDir = "";
722         } else {
723             $relDir =~ s/(.*)\/(.*)/$1/;
724             $currDir = $2;
725         }
726     }
727     $share = $currDir;
728     my $dirDisplay = "$share/$dir";
729     $dirDisplay =~ s{//+}{/}g;
730     $dirDisplay =~ s{/+$}{}g;
731     my $filledBackup;
732
733     if ( (my @mergeNums = @{$view->mergeNums}) > 1 ) {
734         shift(@mergeNums);
735         my $numF = join(", #", @mergeNums);
736         $filledBackup = eval("qq{$Lang->{This_display_is_merged_with_backup}}");
737     }
738     Header(eval("qq{$Lang->{Browse_backup__num_for__host}}"));
739
740     foreach my $d ( @DirStrPrev ) {
741         $dirStr .= "<tr><td$d->{tdArgs}>$d->{link}\n";
742     }
743
744     ### hide checkall button if there are no files
745     my ($topCheckAll, $checkAll, $fileHeader);
746     if ( $fileStr ) {
747         $fileHeader = eval("qq{$Lang->{fileHeader}}");
748
749         $checkAll = $Lang->{checkAll};
750
751         # and put a checkall box on top if there are at least 20 files
752         if ( $checkBoxCnt >= 20 ) {
753             $topCheckAll = $checkAll;
754             $topCheckAll =~ s{allFiles}{allFilestop}g;
755         }
756     } else {
757         $fileStr = eval("qq{$Lang->{The_directory_is_empty}}");
758     }
759     my @otherDirs;
760     foreach my $i ( $view->backupList($share, $dir) ) {
761         my $path = $dir;
762         my $shareURI = $share;
763         $path =~ s/([^\w.\/-])/uc sprintf("%%%02x", ord($1))/eg;
764         $shareURI =~ s/([^\w.\/-])/uc sprintf("%%%02x", ord($1))/eg;
765         push(@otherDirs, "<a href=\"$MyURL?action=browse&host=${EscURI($host)}&num=$i"
766                        . "&share=$shareURI&dir=$path\">$i</a>");
767
768     }
769     if ( @otherDirs ) {
770         my $otherDirs  = join(",\n", @otherDirs);
771         $filledBackup .= eval("qq{$Lang->{Visit_this_directory_in_backup}}");
772     }
773     print (eval("qq{$Lang->{Backup_browse_for__host}}"));
774     Trailer();
775 }
776
777 sub Action_Restore
778 {
779     my($str, $reply);
780     my $Privileged = CheckPermission($In{host});
781     if ( !$Privileged ) {
782         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_restore_backup_files}}"));
783     }
784     my $host  = $In{host};
785     my $num   = $In{num};
786     my $share = $In{share};
787     my(@fileList, $fileListStr, $hiddenStr, $pathHdr, $badFileCnt);
788     my @Backups = $bpc->BackupInfoRead($host);
789
790     ServerConnect();
791     if ( !defined($Hosts->{$host}) ) {
792         ErrorExit(eval("qq{$Lang->{Bad_host_name}}"));
793     }
794     for ( my $i = 0 ; $i < $In{fcbMax} ; $i++ ) {
795         next if ( !defined($In{"fcb$i"}) );
796         (my $name = $In{"fcb$i"}) =~ s/%([0-9A-F]{2})/chr(hex($1))/eg;
797         $badFileCnt++ if ( $name =~ m{(^|/)\.\.(/|$)} );
798         if ( @fileList == 0 ) {
799             $pathHdr = $name;
800         } else {
801             while ( substr($name, 0, length($pathHdr)) ne $pathHdr ) {
802                 $pathHdr = substr($pathHdr, 0, rindex($pathHdr, "/"));
803             }
804         }
805         push(@fileList, $name);
806         $hiddenStr .= <<EOF;
807 <input type="hidden" name="fcb$i" value="$In{'fcb' . $i}">
808 EOF
809         $fileListStr .= <<EOF;
810 <li> ${EscHTML($name)}
811 EOF
812     }
813     $hiddenStr .= "<input type=\"hidden\" name=\"fcbMax\" value=\"$In{fcbMax}\">\n";
814     $hiddenStr .= "<input type=\"hidden\" name=\"share\" value=\"${EscHTML($share)}\">\n";
815     $badFileCnt++ if ( $In{pathHdr} =~ m{(^|/)\.\.(/|$)} );
816     $badFileCnt++ if ( $In{num} =~ m{(^|/)\.\.(/|$)} );
817     if ( @fileList == 0 ) {
818         ErrorExit($Lang->{You_haven_t_selected_any_files__please_go_Back_to});
819     }
820     if ( $badFileCnt ) {
821         ErrorExit($Lang->{Nice_try__but_you_can_t_put});
822     }
823     if ( @fileList == 1 ) {
824         $pathHdr =~ s/(.*)\/.*/$1/;
825     }
826     $pathHdr = "/" if ( $pathHdr eq "" );
827     if ( $In{type} != 0 && @fileList == $In{fcbMax} ) {
828         #
829         # All the files in the list were selected, so just restore the
830         # entire parent directory
831         #
832         @fileList = ( $pathHdr );
833     }
834     if ( $In{type} == 0 ) {
835         #
836         # Tell the user what options they have
837         #
838         Header(eval("qq{$Lang->{Restore_Options_for__host}}"));
839         print(eval("qq{$Lang->{Restore_Options_for__host2}}"));
840
841         #
842         # Verify that Archive::Zip is available before showing the
843         # zip restore option
844         #
845         if ( eval { require Archive::Zip } ) {
846             print (eval("qq{$Lang->{Option_2__Download_Zip_archive}}"));
847         } else {
848             print (eval("qq{$Lang->{Option_2__Download_Zip_archive2}}"));
849         }
850         print (eval("qq{$Lang->{Option_3__Download_Zip_archive}}"));
851         Trailer();
852     } elsif ( $In{type} == 1 ) {
853         #
854         # Provide the selected files via a tar archive.
855         #
856         # We no longer use fork/exec (as in v1.5.0) since some mod_perls
857         # do not correctly preserve the stdout connection to the client
858         # browser, so we execute BackupPC_tarCreate in-line.
859         #
860         my @fileListTrim = @fileList;
861         if ( @fileListTrim > 10 ) {
862             @fileListTrim = (@fileListTrim[0..9], '...');
863         }
864         $bpc->ServerMesg(eval("qq{$Lang->{log_User__User_downloaded_tar_archive_for__host}}"));
865
866         my @pathOpts;
867         if ( $In{relative} ) {
868             @pathOpts = ("-r", $pathHdr, "-p", "");
869         }
870         #
871         # We use syswrite since BackupPC_tarCreate uses syswrite too.
872         # Need to test this with mod_perl: PaulL says it doesn't work.
873         #
874         syswrite(STDOUT, <<EOF);
875 Content-Type: application/x-gtar
876 Content-Transfer-Encoding: binary
877 Content-Disposition: attachment; filename=\"restore.tar\"
878
879 EOF
880         local(@ARGV);
881         @ARGV = (
882              "-h", $host,
883              "-n", $num,
884              "-s", $share,
885              @pathOpts,
886              @fileList
887         );
888         do "$BinDir/BackupPC_tarCreate";
889     } elsif ( $In{type} == 2 ) {
890         #
891         # Provide the selected files via a zip archive.
892         #
893         # We no longer use fork/exec (as in v1.5.0) since some mod_perls
894         # do not correctly preserve the stdout connection to the client
895         # browser, so we execute BackupPC_tarCreate in-line.
896         #
897         my @fileListTrim = @fileList;
898         if ( @fileListTrim > 10 ) {
899             @fileListTrim = (@fileListTrim[0..9], '...');
900         }
901         $bpc->ServerMesg(eval("qq{$Lang->{log_User__User_downloaded_zip_archive_for__host}}"));
902
903         my @pathOpts;
904         if ( $In{relative} ) {
905             @pathOpts = ("-r", $pathHdr, "-p", "");
906         }
907         #
908         # We use syswrite since BackupPC_tarCreate uses syswrite too.
909         # Need to test this with mod_perl: PaulL says it doesn't work.
910         #
911         syswrite(STDOUT, <<EOF);
912 Content-Type: application/zip
913 Content-Transfer-Encoding: binary
914 Content-Disposition: attachment; filename=\"restore.zip\"
915
916 EOF
917         $In{compressLevel} = 5 if ( $In{compressLevel} !~ /^\d+$/ );
918         local(@ARGV);
919         @ARGV = (
920              "-h", $host,
921              "-n", $num,
922              "-c", $In{compressLevel},
923              "-s", $share,
924              @pathOpts,
925              @fileList
926         );
927         do "$BinDir/BackupPC_zipCreate";
928     } elsif ( $In{type} == 3 ) {
929         #
930         # Do restore directly onto host
931         #
932         if ( !defined($Hosts->{$In{hostDest}}) ) {
933             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
934         }
935         if ( !CheckPermission($In{hostDest}) ) {
936             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
937         }
938         $fileListStr = "";
939         foreach my $f ( @fileList ) {
940             my $targetFile = $f;
941             (my $strippedShare = $share) =~ s/^\///;
942             (my $strippedShareDest = $In{shareDest}) =~ s/^\///;
943             substr($targetFile, 0, length($pathHdr)) = $In{pathHdr};
944             $fileListStr .= <<EOF;
945 <tr><td>$host:/$strippedShare$f</td><td>$In{hostDest}:/$strippedShareDest$targetFile</td></tr>
946 EOF
947         }
948         Header(eval("qq{$Lang->{Restore_Confirm_on__host}}"));
949         print(eval("qq{$Lang->{Are_you_sure}}"));
950         Trailer();
951     } elsif ( $In{type} == 4 ) {
952         if ( !defined($Hosts->{$In{hostDest}}) ) {
953             ErrorExit(eval("qq{$Lang->{Host__doesn_t_exist}}"));
954         }
955         if ( !CheckPermission($In{hostDest}) ) {
956             ErrorExit(eval("qq{$Lang->{You_don_t_have_permission_to_restore_onto_host}}"));
957         }
958         my $hostDest = $1 if ( $In{hostDest} =~ /(.+)/ );
959         my $ipAddr = ConfirmIPAddress($hostDest);
960         #
961         # Prepare and send the restore request.  We write the request
962         # information using Data::Dumper to a unique file,
963         # $TopDir/pc/$hostDest/restoreReq.$$.n.  We use a file
964         # in case the list of files to restore is very long.
965         #
966         my $reqFileName;
967         for ( my $i = 0 ; ; $i++ ) {
968             $reqFileName = "restoreReq.$$.$i";
969             last if ( !-f "$TopDir/pc/$hostDest/$reqFileName" );
970         }
971         my %restoreReq = (
972             # source of restore is hostSrc, #num, path shareSrc/pathHdrSrc
973             num         => $In{num},
974             hostSrc     => $host,
975             shareSrc    => $share,
976             pathHdrSrc  => $pathHdr,
977
978             # destination of restore is hostDest:shareDest/pathHdrDest
979             hostDest    => $hostDest,
980             shareDest   => $In{shareDest},
981             pathHdrDest => $In{pathHdr},
982
983             # list of files to restore
984             fileList    => \@fileList,
985
986             # other info
987             user        => $User,
988             reqTime     => time,
989         );
990         my($dump) = Data::Dumper->new(
991                          [  \%restoreReq],
992                          [qw(*RestoreReq)]);
993         $dump->Indent(1);
994         if ( open(REQ, ">$TopDir/pc/$hostDest/$reqFileName") ) {
995             print(REQ $dump->Dump);
996             close(REQ);
997         } else {
998             ErrorExit(eval("qq{$Lang->{Can_t_open_create}}"));
999         }
1000         $reply = $bpc->ServerMesg("restore ${EscURI($ipAddr)}"
1001                         . " ${EscURI($hostDest)} $User $reqFileName");
1002         $str = eval("qq{$Lang->{Restore_requested_to_host__hostDest__backup___num}}");
1003         Header(eval("qq{$Lang->{Restore_Requested_on__hostDest}}"));
1004         print (eval("qq{$Lang->{Reply_from_server_was___reply}}"));
1005         Trailer();
1006     }
1007 }
1008
1009 sub Action_RestoreFile
1010 {
1011     restoreFile($In{host}, $In{num}, $In{share}, $In{dir});
1012 }
1013
1014 sub restoreFile
1015 {
1016     my($host, $num, $share, $dir, $skipHardLink, $origName) = @_;
1017     my($Privileged) = CheckPermission($host);
1018
1019     #
1020     # Some common content (media) types from www.iana.org (via MIME::Types).
1021     #
1022     my $Ext2ContentType = {
1023         'asc'  => 'text/plain',
1024         'avi'  => 'video/x-msvideo',
1025         'bmp'  => 'image/bmp',
1026         'book' => 'application/x-maker',
1027         'cc'   => 'text/plain',
1028         'cpp'  => 'text/plain',
1029         'csh'  => 'application/x-csh',
1030         'csv'  => 'text/comma-separated-values',
1031         'c'    => 'text/plain',
1032         'deb'  => 'application/x-debian-package',
1033         'doc'  => 'application/msword',
1034         'dot'  => 'application/msword',
1035         'dtd'  => 'text/xml',
1036         'dvi'  => 'application/x-dvi',
1037         'eps'  => 'application/postscript',
1038         'fb'   => 'application/x-maker',
1039         'fbdoc'=> 'application/x-maker',
1040         'fm'   => 'application/x-maker',
1041         'frame'=> 'application/x-maker',
1042         'frm'  => 'application/x-maker',
1043         'gif'  => 'image/gif',
1044         'gtar' => 'application/x-gtar',
1045         'gz'   => 'application/x-gzip',
1046         'hh'   => 'text/plain',
1047         'hpp'  => 'text/plain',
1048         'h'    => 'text/plain',
1049         'html' => 'text/html',
1050         'htmlx'=> 'text/html',
1051         'htm'  => 'text/html',
1052         'iges' => 'model/iges',
1053         'igs'  => 'model/iges',
1054         'jpeg' => 'image/jpeg',
1055         'jpe'  => 'image/jpeg',
1056         'jpg'  => 'image/jpeg',
1057         'js'   => 'application/x-javascript',
1058         'latex'=> 'application/x-latex',
1059         'maker'=> 'application/x-maker',
1060         'mid'  => 'audio/midi',
1061         'midi' => 'audio/midi',
1062         'movie'=> 'video/x-sgi-movie',
1063         'mov'  => 'video/quicktime',
1064         'mp2'  => 'audio/mpeg',
1065         'mp3'  => 'audio/mpeg',
1066         'mpeg' => 'video/mpeg',
1067         'mpg'  => 'video/mpeg',
1068         'mpp'  => 'application/vnd.ms-project',
1069         'pdf'  => 'application/pdf',
1070         'pgp'  => 'application/pgp-signature',
1071         'php'  => 'application/x-httpd-php',
1072         'pht'  => 'application/x-httpd-php',
1073         'phtml'=> 'application/x-httpd-php',
1074         'png'  => 'image/png',
1075         'ppm'  => 'image/x-portable-pixmap',
1076         'ppt'  => 'application/powerpoint',
1077         'ppt'  => 'application/vnd.ms-powerpoint',
1078         'ps'   => 'application/postscript',
1079         'qt'   => 'video/quicktime',
1080         'rgb'  => 'image/x-rgb',
1081         'rtf'  => 'application/rtf',
1082         'rtf'  => 'text/rtf',
1083         'shar' => 'application/x-shar',
1084         'shtml'=> 'text/html',
1085         'swf'  => 'application/x-shockwave-flash',
1086         'tex'  => 'application/x-tex',
1087         'texi' => 'application/x-texinfo',
1088         'texinfo'=> 'application/x-texinfo',
1089         'tgz'  => 'application/x-gtar',
1090         'tiff' => 'image/tiff',
1091         'tif'  => 'image/tiff',
1092         'txt'  => 'text/plain',
1093         'vcf'  => 'text/x-vCard',
1094         'vrml' => 'model/vrml',
1095         'wav'  => 'audio/x-wav',
1096         'wmls' => 'text/vnd.wap.wmlscript',
1097         'wml'  => 'text/vnd.wap.wml',
1098         'wrl'  => 'model/vrml',
1099         'xls'  => 'application/vnd.ms-excel',
1100         'xml'  => 'text/xml',
1101         'xwd'  => 'image/x-xwindowdump',
1102         'z'    => 'application/x-compress',
1103         'zip'  => 'application/zip',
1104         %{$Conf{CgiExt2ContentType}},       # add site-specific values
1105     };
1106     if ( !$Privileged ) {
1107         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_restore_backup_files2}}"));
1108     }
1109     ServerConnect();
1110     ErrorExit($Lang->{Empty_host_name}) if ( $host eq "" );
1111
1112     $dir = "/" if ( $dir eq "" );
1113     my @Backups = $bpc->BackupInfoRead($host);
1114     my $view = BackupPC::View->new($bpc, $host, \@Backups);
1115     my $a = $view->fileAttrib($num, $share, $dir);
1116     if ( $dir =~ m{(^|/)\.\.(/|$)} || !defined($a) ) {
1117         ErrorExit("Can't restore bad file ${EscHTML($dir)}");
1118     }
1119     my $f = BackupPC::FileZIO->open($a->{fullPath}, 0, $a->{compress});
1120     my $data;
1121     if ( !$skipHardLink && $a->{type} == BPC_FTYPE_HARDLINK ) {
1122         #
1123         # hardlinks should look like the file they point to
1124         #
1125         my $linkName;
1126         while ( $f->read(\$data, 65536) > 0 ) {
1127             $linkName .= $data;
1128         }
1129         $f->close;
1130         $linkName =~ s/^\.\///;
1131         my $share = $1 if ( $dir =~ /^\/?(.*?)\// );
1132         restoreFile($host, $num, $share, $linkName, 1, $dir);
1133         return;
1134     }
1135     $bpc->ServerMesg("log User $User recovered file $host/$num:$share/$dir ($a->{fullPath})");
1136     $dir = $origName if ( defined($origName) );
1137     my $ext = $1 if ( $dir =~ /\.([^\/\.]+)$/ );
1138     my $contentType = $Ext2ContentType->{lc($ext)}
1139                                     || "application/octet-stream";
1140     my $fileName = $1 if ( $dir =~ /.*\/(.*)/ );
1141     $fileName =~ s/"/\\"/g;
1142     print "Content-Type: $contentType\n";
1143     print "Content-Transfer-Encoding: binary\n";
1144     print "Content-Disposition: attachment; filename=\"$fileName\"\n\n";
1145     while ( $f->read(\$data, 1024 * 1024) > 0 ) {
1146         print STDOUT $data;
1147     }
1148     $f->close;
1149 }
1150
1151 sub Action_HostInfo
1152 {
1153     my $host = $1 if ( $In{host} =~ /(.*)/ );
1154     my($statusStr, $startIncrStr);
1155
1156     $host =~ s/^\s+//;
1157     $host =~ s/\s+$//;
1158     return Action_GeneralInfo() if ( $host eq "" );
1159     $host = lc($host)
1160                 if ( !-d "$TopDir/pc/$host" && -d "$TopDir/pc/" . lc($host) );
1161     if ( $host =~ /\.\./ || !-d "$TopDir/pc/$host" ) {
1162         #
1163         # try to lookup by user name
1164         #
1165         if ( !defined($Hosts->{$host}) ) {
1166             foreach my $h ( keys(%$Hosts) ) {
1167                 if ( $Hosts->{$h}{user} eq $host
1168                         || lc($Hosts->{$h}{user}) eq lc($host) ) {
1169                     $host = $h;
1170                     last;
1171                 }
1172             }
1173             CheckPermission();
1174             ErrorExit(eval("qq{$Lang->{Unknown_host_or_user}}"))
1175                                 if ( !defined($Hosts->{$host}) );
1176         }
1177         $In{host} = $host;
1178     }
1179     GetStatusInfo("host(${EscURI($host)})");
1180     $bpc->ConfigRead($host);
1181     %Conf = $bpc->Conf();
1182     my $Privileged = CheckPermission($host);
1183     if ( !$Privileged ) {
1184         ErrorExit(eval("qq{$Lang->{Only_privileged_users_can_view_information_about}}"));
1185     }
1186     ReadUserEmailInfo();
1187
1188     my @Backups = $bpc->BackupInfoRead($host);
1189     my($str, $sizeStr, $compStr, $errStr, $warnStr);
1190     for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1191         my $startTime = timeStamp2($Backups[$i]{startTime});
1192         my $dur       = $Backups[$i]{endTime} - $Backups[$i]{startTime};
1193         $dur          = 1 if ( $dur <= 0 );
1194         my $duration  = sprintf("%.1f", $dur / 60);
1195         my $MB        = sprintf("%.1f", $Backups[$i]{size} / (1024*1024));
1196         my $MBperSec  = sprintf("%.2f", $Backups[$i]{size} / (1024*1024*$dur));
1197         my $MBExist   = sprintf("%.1f", $Backups[$i]{sizeExist} / (1024*1024));
1198         my $MBNew     = sprintf("%.1f", $Backups[$i]{sizeNew} / (1024*1024));
1199         my($MBExistComp, $ExistComp, $MBNewComp, $NewComp);
1200         if ( $Backups[$i]{sizeExist} && $Backups[$i]{sizeExistComp} ) {
1201             $MBExistComp = sprintf("%.1f", $Backups[$i]{sizeExistComp}
1202                                                 / (1024 * 1024));
1203             $ExistComp = sprintf("%.1f%%", 100 *
1204                   (1 - $Backups[$i]{sizeExistComp} / $Backups[$i]{sizeExist}));
1205         }
1206         if ( $Backups[$i]{sizeNew} && $Backups[$i]{sizeNewComp} ) {
1207             $MBNewComp = sprintf("%.1f", $Backups[$i]{sizeNewComp}
1208                                                 / (1024 * 1024));
1209             $NewComp = sprintf("%.1f%%", 100 *
1210                   (1 - $Backups[$i]{sizeNewComp} / $Backups[$i]{sizeNew}));
1211         }
1212         my $age = sprintf("%.1f", (time - $Backups[$i]{startTime}) / (24*3600));
1213         my $browseURL = "$MyURL?action=browse&host=${EscURI($host)}&num=$Backups[$i]{num}";
1214         my $filled = $Backups[$i]{noFill} ? $Lang->{No} : $Lang->{Yes};
1215         $filled .= " ($Backups[$i]{fillFromNum}) "
1216                             if ( $Backups[$i]{fillFromNum} ne "" );
1217         my $ltype;
1218         if ($Backups[$i]{type} eq "full") { $ltype = $Lang->{full}; }
1219         else { $ltype = $Lang->{incremental}; }
1220         $str .= <<EOF;
1221 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1222     <td align="center"> $ltype </td>
1223     <td align="center"> $filled </td>
1224     <td align="right">  $startTime </td>
1225     <td align="right">  $duration </td>
1226     <td align="right">  $age </td>
1227     <td align="left">   <tt>$TopDir/pc/$host/$Backups[$i]{num}</tt> </td></tr>
1228 EOF
1229         $sizeStr .= <<EOF;
1230 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1231     <td align="center"> $ltype </td>
1232     <td align="right">  $Backups[$i]{nFiles} </td>
1233     <td align="right">  $MB </td>
1234     <td align="right">  $MBperSec </td>
1235     <td align="right">  $Backups[$i]{nFilesExist} </td>
1236     <td align="right">  $MBExist </td>
1237     <td align="right">  $Backups[$i]{nFilesNew} </td>
1238     <td align="right">  $MBNew </td>
1239 </tr>
1240 EOF
1241         my $is_compress = $Backups[$i]{compress} || $Lang->{off};
1242         if (! $ExistComp) { $ExistComp = "&nbsp;"; }
1243         if (! $MBExistComp) { $MBExistComp = "&nbsp;"; }
1244         $compStr .= <<EOF;
1245 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1246     <td align="center"> $ltype </td>
1247     <td align="center"> $is_compress </td> 
1248     <td align="right">  $MBExist </td>
1249     <td align="right">  $MBExistComp </td> 
1250     <td align="right">  $ExistComp </td>   
1251     <td align="right">  $MBNew </td>
1252     <td align="right">  $MBNewComp </td>
1253     <td align="right">  $NewComp </td>
1254 </tr>
1255 EOF
1256         $errStr .= <<EOF;
1257 <tr><td align="center"> <a href="$browseURL">$Backups[$i]{num}</a> </td>
1258     <td align="center"> $ltype </td>
1259     <td align="center"> <a href="$MyURL?action=view&type=XferLOG&num=$Backups[$i]{num}&host=${EscURI($host)}">XferLOG</a>,
1260                       <a href="$MyURL?action=view&type=XferErr&num=$Backups[$i]{num}&host=${EscURI($host)}">Errors</a> </td>
1261     <td align="right">  $Backups[$i]{xferErrs} </td>
1262     <td align="right">  $Backups[$i]{xferBadFile} </td>
1263     <td align="right">  $Backups[$i]{xferBadShare} </td>
1264     <td align="right">  $Backups[$i]{tarErrs} </td></tr>
1265 EOF
1266     }
1267
1268     my @Restores = $bpc->RestoreInfoRead($host);
1269     my $restoreStr;
1270
1271     for ( my $i = 0 ; $i < @Restores ; $i++ ) {
1272         my $startTime = timeStamp2($Restores[$i]{startTime});
1273         my $dur       = $Restores[$i]{endTime} - $Restores[$i]{startTime};
1274         $dur          = 1 if ( $dur <= 0 );
1275         my $duration  = sprintf("%.1f", $dur / 60);
1276         my $MB        = sprintf("%.1f", $Restores[$i]{size} / (1024*1024));
1277         my $MBperSec  = sprintf("%.2f", $Restores[$i]{size} / (1024*1024*$dur));
1278         my $Restores_Result = $Lang->{failed};
1279         if ($Restores[$i]{result} ne "failed") { $Restores_Result = $Lang->{success}; }
1280         $restoreStr  .= <<EOF;
1281 <tr><td align="center"><a href="$MyURL?action=restoreInfo&num=$Restores[$i]{num}&host=${EscURI($host)}">$Restores[$i]{num}</a> </td>
1282     <td align="center"> $Restores_Result </td>
1283     <td align="right"> $startTime </td>
1284     <td align="right"> $duration </td>
1285     <td align="right"> $Restores[$i]{nFiles} </td>
1286     <td align="right"> $MB </td>
1287     <td align="right"> $Restores[$i]{tarCreateErrs} </td>
1288     <td align="right"> $Restores[$i]{xferErrs} </td>
1289 </tr>
1290 EOF
1291     }
1292     if ( $restoreStr ne "" ) {
1293         $restoreStr = eval("qq{$Lang->{Restore_Summary}}");
1294     }
1295     if ( @Backups == 0 ) {
1296         $warnStr = $Lang->{This_PC_has_never_been_backed_up};
1297     }
1298     if ( defined($Hosts->{$host}) ) {
1299         my $user = $Hosts->{$host}{user};
1300         my @moreUsers = sort(keys(%{$Hosts->{$host}{moreUsers}}));
1301         my $moreUserStr;
1302         foreach my $u ( sort(keys(%{$Hosts->{$host}{moreUsers}})) ) {
1303             $moreUserStr .= ", " if ( $moreUserStr ne "" );
1304             $moreUserStr .= "${UserLink($u)}";
1305         }
1306         if ( $moreUserStr ne "" ) {
1307             $moreUserStr = " ($Lang->{and} $moreUserStr).\n";
1308         } else {
1309             $moreUserStr = ".\n";
1310         }
1311         if ( $user ne "" ) {
1312             $statusStr .= eval("qq{$Lang->{This_PC_is_used_by}$moreUserStr}");
1313         }
1314         if ( defined($UserEmailInfo{$user})
1315                 && $UserEmailInfo{$user}{lastHost} eq $host ) {
1316             my $mailTime = timeStamp2($UserEmailInfo{$user}{lastTime});
1317             my $subj     = $UserEmailInfo{$user}{lastSubj};
1318             $statusStr  .= eval("qq{$Lang->{Last_email_sent_to__was_at___subject}}");
1319         }
1320     }
1321     if ( defined($Jobs{$host}) ) {
1322         my $startTime = timeStamp2($Jobs{$host}{startTime});
1323         (my $cmd = $Jobs{$host}{cmd}) =~ s/$BinDir\///g;
1324         $statusStr .= eval("qq{$Lang->{The_command_cmd_is_currently_running_for_started}}");
1325     }
1326     if ( $StatusHost{BgQueueOn} ) {
1327         $statusStr .= eval("qq{$Lang->{Host_host_is_queued_on_the_background_queue_will_be_backed_up_soon}}");
1328     }
1329     if ( $StatusHost{UserQueueOn} ) {
1330         $statusStr .= eval("qq{$Lang->{Host_host_is_queued_on_the_user_queue__will_be_backed_up_soon}}");
1331     }
1332     if ( $StatusHost{CmdQueueOn} ) {
1333         $statusStr .= eval("qq{$Lang->{A_command_for_host_is_on_the_command_queue_will_run_soon}}");
1334     }
1335     my $startTime = timeStamp2($StatusHost{endTime} == 0 ?
1336                 $StatusHost{startTime} : $StatusHost{endTime});
1337     my $reason = "";
1338     if ( $StatusHost{reason} ne "" ) {
1339         $reason = " ($Lang->{$StatusHost{reason}})";
1340     }
1341     $statusStr .= eval("qq{$Lang->{Last_status_is_state_StatusHost_state_reason_as_of_startTime}}");
1342
1343     if ( $StatusHost{error} ne "" ) {
1344         $statusStr .= eval("qq{$Lang->{Last_error_is____EscHTML_StatusHost_error}}");
1345     }
1346     my $priorStr = "Pings";
1347     if ( $StatusHost{deadCnt} > 0 ) {
1348         $statusStr .= eval("qq{$Lang->{Pings_to_host_have_failed_StatusHost_deadCnt__consecutive_times}}");
1349         $priorStr = $Lang->{Prior_to_that__pings};
1350     }
1351     if ( $StatusHost{aliveCnt} > 0 ) {
1352         $statusStr .= eval("qq{$Lang->{priorStr_to_host_have_succeeded_StatusHostaliveCnt_consecutive_times}}");
1353
1354         if ( $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt}
1355                 && $Conf{BlackoutGoodCnt} >= 0 && $Conf{BlackoutHourBegin} >= 0
1356                 && $Conf{BlackoutHourEnd} >= 0 ) {
1357             my(@days) = qw(Sun Mon Tue Wed Thu Fri Sat);
1358             my($days) = join(", ", @days[@{$Conf{BlackoutWeekDays}}]);
1359             my($t0) = sprintf("%d:%02d", $Conf{BlackoutHourBegin},
1360                             60 * ($Conf{BlackoutHourBegin}
1361                                      - int($Conf{BlackoutHourBegin})));
1362             my($t1) = sprintf("%d:%02d", $Conf{BlackoutHourEnd},
1363                             60 * ($Conf{BlackoutHourEnd}
1364                                      - int($Conf{BlackoutHourEnd})));
1365             $statusStr .= eval("qq{$Lang->{Because__host_has_been_on_the_network_at_least__Conf_BlackoutGoodCnt_consecutive_times___}}");
1366         }
1367     }
1368     if ( $StatusHost{backoffTime} > time ) {
1369         my $hours = sprintf("%.1f", ($StatusHost{backoffTime} - time) / 3600);
1370         $statusStr .= eval("qq{$Lang->{Backups_are_deferred_for_hours_hours_change_this_number}}");
1371
1372     }
1373     if ( @Backups ) {
1374         # only allow incremental if there are already some backups
1375         $startIncrStr = <<EOF;
1376 <input type="submit" value="\$Lang->{Start_Incr_Backup}" name="action">
1377 EOF
1378     }
1379
1380     $startIncrStr = eval ("qq{$startIncrStr}");
1381
1382     Header(eval("qq{$Lang->{Host__host_Backup_Summary}}"));
1383     print(eval("qq{$Lang->{Host__host_Backup_Summary2}}"));
1384     Trailer();
1385 }
1386
1387 sub Action_GeneralInfo
1388 {
1389     GetStatusInfo("info jobs hosts queueLen");
1390     my $Privileged = CheckPermission();
1391
1392     my($jobStr, $statusStr, $tarPidHdr);
1393     foreach my $host ( sort(keys(%Jobs)) ) {
1394         my $startTime = timeStamp2($Jobs{$host}{startTime});
1395         next if ( $host eq $bpc->trashJob
1396                     && $Jobs{$host}{processState} ne "running" );
1397         $Jobs{$host}{type} = $Status{$host}{type}
1398                     if ( $Jobs{$host}{type} eq "" && defined($Status{$host}));
1399         (my $cmd = $Jobs{$host}{cmd}) =~ s/$BinDir\///g;
1400         $jobStr .= <<EOF;
1401 <tr><td> ${HostLink($host)} </td>
1402     <td align="center"> $Jobs{$host}{type} </td>
1403     <td align="center"> ${UserLink($Hosts->{$host}{user})} </td>
1404     <td> $startTime </td>
1405     <td> $cmd </td>
1406     <td align="center"> $Jobs{$host}{pid} </td>
1407     <td align="center"> $Jobs{$host}{xferPid} </td>
1408 EOF
1409         if ( $Jobs{$host}{tarPid} > 0 ) {
1410             $jobStr .= "    <td align=\"center\"> $Jobs{$host}{tarPid} </td>\n";
1411             $tarPidHdr ||= "<td align=\"center\"> tar PID </td>\n";
1412         }
1413         $jobStr .= "</tr>\n";
1414     }
1415     foreach my $host ( sort(keys(%Status)) ) {
1416         next if ( $Status{$host}{reason} ne "Reason_backup_failed" );
1417         my $startTime = timeStamp2($Status{$host}{startTime});
1418         my($errorTime, $XferViewStr);
1419         if ( $Status{$host}{errorTime} > 0 ) {
1420             $errorTime = timeStamp2($Status{$host}{errorTime});
1421         }
1422         if ( -f "$TopDir/pc/$host/SmbLOG.bad"
1423                 || -f "$TopDir/pc/$host/SmbLOG.bad.z"
1424                 || -f "$TopDir/pc/$host/XferLOG.bad"
1425                 || -f "$TopDir/pc/$host/XferLOG.bad.z"
1426                 ) {
1427             $XferViewStr = <<EOF;
1428 <a href="$MyURL?action=view&type=XferLOGbad&host=${EscURI($host)}">XferLOG</a>,
1429 <a href="$MyURL?action=view&type=XferErrbad&host=${EscURI($host)}">XferErr</a>
1430 EOF
1431         } else {
1432             $XferViewStr = "";
1433         }
1434         (my $shortErr = $Status{$host}{error}) =~ s/(.{48}).*/$1.../;   
1435         $statusStr .= <<EOF;
1436 <tr><td> ${HostLink($host)} </td>
1437     <td align="center"> $Status{$host}{type} </td>
1438     <td align="center"> ${UserLink($Hosts->{$host}{user})} </td>
1439     <td align="right"> $startTime </td>
1440     <td> $XferViewStr </td>
1441     <td align="right"> $errorTime </td>
1442     <td> ${EscHTML($shortErr)} </td></tr>
1443 EOF
1444     }
1445     my $now          = timeStamp2(time);
1446     my $nextWakeupTime = timeStamp2($Info{nextWakeup});
1447     my $DUlastTime   = timeStamp2($Info{DUlastValueTime});
1448     my $DUmaxTime    = timeStamp2($Info{DUDailyMaxTime});
1449     my $numBgQueue   = $QueueLen{BgQueue};
1450     my $numUserQueue = $QueueLen{UserQueue};
1451     my $numCmdQueue  = $QueueLen{CmdQueue};
1452     my $serverStartTime = timeStamp2($Info{startTime});
1453     my $poolInfo     = genPoolInfo("pool", \%Info);
1454     my $cpoolInfo    = genPoolInfo("cpool", \%Info);
1455     if ( $Info{poolFileCnt} > 0 && $Info{cpoolFileCnt} > 0 ) {
1456         $poolInfo = <<EOF;
1457 <li>Uncompressed pool:
1458 <ul>
1459 $poolInfo
1460 </ul>
1461 <li>Compressed pool:
1462 <ul>
1463 $cpoolInfo
1464 </ul>
1465 EOF
1466     } elsif ( $Info{cpoolFileCnt} > 0 ) {
1467         $poolInfo = $cpoolInfo;
1468     }
1469
1470     Header($Lang->{H_BackupPC_Server_Status});
1471         #Header("H_BackupPC_Server_Status");
1472     print (eval ("qq{$Lang->{BackupPC_Server_Status}}"));
1473
1474     #Header($Lang->{BackupPC_Server_Status});
1475
1476     #my $trans_text = $Lang->{BackupPC_Server_Status};
1477     #print eval ("qq{$trans_text}");
1478     Trailer();
1479 }
1480
1481 sub Action_RestoreInfo
1482 {
1483     my $Privileged = CheckPermission($In{host});
1484     my $host = $1 if ( $In{host} =~ /(.*)/ );
1485     my $num  = $In{num};
1486     my $i;
1487
1488     if ( !$Privileged ) {
1489         ErrorExit($Lang->{Only_privileged_users_can_view_restore_information});
1490     }
1491     #
1492     # Find the requested restore
1493     #
1494     my @Restores = $bpc->RestoreInfoRead($host);
1495     for ( $i = 0 ; $i < @Restores ; $i++ ) {
1496         last if ( $Restores[$i]{num} == $num );
1497     }
1498     if ( $i >= @Restores ) {
1499         ErrorExit(eval("qq{$Lang->{Restore_number__num_for_host__does_not_exist}}"));
1500     }
1501
1502     %RestoreReq = ();
1503     do "$TopDir/pc/$host/RestoreInfo.$Restores[$i]{num}"
1504             if ( -f "$TopDir/pc/$host/RestoreInfo.$Restores[$i]{num}" );
1505
1506     my $startTime = timeStamp2($Restores[$i]{startTime});
1507     my $reqTime   = timeStamp2($RestoreReq{reqTime});
1508     my $dur       = $Restores[$i]{endTime} - $Restores[$i]{startTime};
1509     $dur          = 1 if ( $dur <= 0 );
1510     my $duration  = sprintf("%.1f", $dur / 60);
1511     my $MB        = sprintf("%.1f", $Restores[$i]{size} / (1024*1024));
1512     my $MBperSec  = sprintf("%.2f", $Restores[$i]{size} / (1024*1024*$dur));
1513
1514     my $fileListStr = "";
1515     foreach my $f ( @{$RestoreReq{fileList}} ) {
1516         my $targetFile = $f;
1517         (my $strippedShareSrc  = $RestoreReq{shareSrc}) =~ s/^\///;
1518         (my $strippedShareDest = $RestoreReq{shareDest}) =~ s/^\///;
1519         substr($targetFile, 0, length($RestoreReq{pathHdrSrc}))
1520                                         = $RestoreReq{pathHdrDest};
1521         $fileListStr .= <<EOF;
1522 <tr><td>$RestoreReq{hostSrc}:/$strippedShareSrc$f</td><td>$RestoreReq{hostDest}:/$strippedShareDest$targetFile</td></tr>
1523 EOF
1524     }
1525
1526     Header(eval("qq{$Lang->{Restore___num_details_for__host}}"));
1527     print(eval("qq{$Lang->{Restore___num_details_for__host2 }}"));
1528     Trailer();
1529 }
1530     
1531 ###########################################################################
1532 # Miscellaneous subroutines
1533 ###########################################################################
1534
1535 sub timeStamp2
1536 {
1537     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
1538               = localtime($_[0] == 0 ? time : $_[0] );
1539     $year += 1900;
1540     $mon++;
1541     if ( $Conf{CgiDateFormatMMDD} ) {
1542         return sprintf("$mon/$mday %02d:%02d", $hour, $min);
1543     } else {
1544         return sprintf("$mday/$mon %02d:%02d", $hour, $min);
1545     }
1546 }
1547
1548 sub HostLink
1549 {
1550     my($host) = @_;
1551     my($s);
1552     if ( defined($Hosts->{$host}) || defined($Status{$host}) ) {
1553         $s = "<a href=\"$MyURL?host=${EscURI($host)}\">$host</a>";
1554     } else {
1555         $s = $host;
1556     }
1557     return \$s;
1558 }
1559
1560 sub UserLink
1561 {
1562     my($user) = @_;
1563     my($s);
1564
1565     return \$user if ( $user eq ""
1566                     || $Conf{CgiUserUrlCreate} eq "" );
1567     if ( $Conf{CgiUserHomePageCheck} eq ""
1568             || -f sprintf($Conf{CgiUserHomePageCheck}, $user, $user, $user) ) {
1569         $s = "<a href=\""
1570              . sprintf($Conf{CgiUserUrlCreate}, $user, $user, $user)
1571              . "\">$user</a>";
1572     } else {
1573         $s = $user;
1574     }
1575     return \$s;
1576 }
1577
1578 sub EscHTML
1579 {
1580     my($s) = @_;
1581     $s =~ s/&/&amp;/g;
1582     $s =~ s/\"/&quot;/g;
1583     $s =~ s/>/&gt;/g;
1584     $s =~ s/</&lt;/g;
1585     $s =~ s{([^[:print:]])}{sprintf("&\#x%02X;", ord($1));}eg;
1586     return \$s;
1587 }
1588
1589 sub EscURI
1590 {
1591     my($s) = @_;
1592     $s =~ s{([^\w.\/-])}{sprintf("%%%02X", ord($1));}eg;
1593     return \$s;
1594 }
1595
1596 sub ErrorExit
1597 {
1598     my(@mesg) = @_;
1599     my($head) = shift(@mesg);
1600     my($mesg) = join("</p>\n<p>", @mesg);
1601     $Conf{CgiHeaderFontType} ||= "arial"; 
1602     $Conf{CgiHeaderFontSize} ||= "3";  
1603     $Conf{CgiNavBarBgColor}  ||= "#ddeeee";
1604     $Conf{CgiHeaderBgColor}  ||= "#99cc33";
1605
1606     $bpc->ServerMesg("log User $User (host=$In{host}) got CGI error: $head")
1607                             if ( defined($bpc) );
1608     if ( !defined($Lang->{Error}) ) {
1609         Header("BackupPC: Error");
1610         $mesg = <<EOF if ( !defined($mesg) );
1611 There is some problem with the BackupPC installation.
1612 Please check the permissions on BackupPC_Admin.
1613 EOF
1614         print <<EOF;
1615 ${h1("Error: Unable to read config.pl or language strings!!")}
1616 <p>$mesg</p>
1617 EOF
1618         Trailer();
1619     } else {
1620         Header(eval("qq{$Lang->{Error}}"));
1621         print (eval("qq{$Lang->{Error____head}}"));
1622         Trailer();
1623     }
1624     exit(1);
1625 }
1626
1627 sub ServerConnect
1628 {
1629     #
1630     # Verify that the server connection is ok
1631     #
1632     return if ( $bpc->ServerOK() );
1633     $bpc->ServerDisconnect();
1634     if ( my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort}) ) {
1635         ErrorExit(eval("qq{$Lang->{Unable_to_connect_to_BackupPC_server}}"));
1636     }
1637 }
1638
1639 sub GetStatusInfo
1640 {
1641     my($status) = @_;
1642     ServerConnect();
1643     my $reply = $bpc->ServerMesg("status $status");
1644     $reply = $1 if ( $reply =~ /(.*)/s );
1645     eval($reply);
1646     # ignore status related to admin and trashClean jobs
1647     if ( $status =~ /\bhosts\b/ ) {
1648         delete($Status{$bpc->adminJob});
1649         delete($Status{$bpc->trashJob});
1650     }
1651 }
1652
1653 sub ReadUserEmailInfo
1654 {
1655     if ( (stat("$TopDir/log/UserEmailInfo.pl"))[9] != $UserEmailInfoMTime ) {
1656         do "$TopDir/log/UserEmailInfo.pl";
1657         $UserEmailInfoMTime = (stat("$TopDir/log/UserEmailInfo.pl"))[9];
1658     }
1659 }
1660
1661 #
1662 # Check if the user is privileged.  A privileged user can access
1663 # any information (backup files, logs, status pages etc).
1664 #
1665 # A user is privileged if they belong to the group
1666 # $Conf{CgiAdminUserGroup}, or they are in $Conf{CgiAdminUsers}
1667 # or they are the user assigned to a host in the host file.
1668 #
1669 sub CheckPermission
1670 {
1671     my($host) = @_;
1672     my $Privileged = 0;
1673
1674     return 0 if ( $User eq "" || ($host ne "" && !defined($Hosts->{$host})) );
1675     if ( $Conf{CgiAdminUserGroup} ne "" ) {
1676         my($n,$p,$gid,$mem) = getgrnam($Conf{CgiAdminUserGroup});
1677         $Privileged ||= ($mem =~ /\b$User\b/);
1678     }
1679     if ( $Conf{CgiAdminUsers} ne "" ) {
1680         $Privileged ||= ($Conf{CgiAdminUsers} =~ /\b$User\b/);
1681         $Privileged ||= $Conf{CgiAdminUsers} eq "*";
1682     }
1683     $PrivAdmin = $Privileged;
1684     $Privileged ||= $User eq $Hosts->{$host}{user};
1685     $Privileged ||= defined($Hosts->{$host}{operators}{$User});
1686
1687     return $Privileged;
1688 }
1689
1690 #
1691 # Returns the list of hosts that should appear in the navigation bar
1692 # for this user.  If $Conf{CgiNavBarAdminAllHosts} is set, the admin
1693 # gets all the hosts.  Otherwise, regular users get hosts for which
1694 # they are the user or are listed in the moreUsers column in the
1695 # hosts file.
1696 #
1697 sub GetUserHosts
1698 {
1699     if ( $Conf{CgiNavBarAdminAllHosts} && CheckPermission() ) {
1700        return sort keys %$Hosts;
1701     }
1702
1703     return sort grep { $Hosts->{$_}{user} eq $User ||
1704                        defined($Hosts->{$_}{moreUsers}{$User}) } keys(%$Hosts);
1705 }
1706
1707 #
1708 # Given a host name tries to find the IP address.  For non-dhcp hosts
1709 # we just return the host name.  For dhcp hosts we check the address
1710 # the user is using ($ENV{REMOTE_ADDR}) and also the last-known IP
1711 # address for $host.  (Later we should replace this with a broadcast
1712 # nmblookup.)
1713 #
1714 sub ConfirmIPAddress
1715 {
1716     my($host) = @_;
1717     my $ipAddr = $host;
1718
1719     if ( $Hosts->{$host}{dhcp}
1720                && $ENV{REMOTE_ADDR} =~ /^(\d+[\.\d]*)$/ ) {
1721         $ipAddr = $1;
1722         my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($ipAddr);
1723         if ( $netBiosHost ne $host ) {
1724             my($tryIP);
1725             GetStatusInfo("host(${EscURI($host)})");
1726             if ( defined($StatusHost{dhcpHostIP})
1727                         && $StatusHost{dhcpHostIP} ne $ipAddr ) {
1728                 $tryIP = eval("qq{$Lang->{tryIP}}");
1729                 ($netBiosHost, $netBiosUser)
1730                         = $bpc->NetBiosInfoGet($StatusHost{dhcpHostIP});
1731             }
1732             if ( $netBiosHost ne $host ) {
1733                 ErrorExit(eval("qq{$Lang->{Can_t_find_IP_address_for}}"),
1734                           eval("qq{$Lang->{host_is_a_DHCP_host}}"));
1735             }
1736             $ipAddr = $StatusHost{dhcpHostIP};
1737         }
1738     }
1739     return $ipAddr;
1740 }
1741
1742 sub genPoolInfo
1743 {
1744     my($name, $info) = @_;
1745     my $poolSize   = sprintf("%.2f", $info->{"${name}Kb"} / (1000 * 1024));
1746     my $poolRmSize = sprintf("%.2f", $info->{"${name}KbRm"} / (1000 * 1024));
1747     my $poolTime   = timeStamp2($info->{"${name}Time"});
1748     $info->{"${name}FileCntRm"} = $info->{"${name}FileCntRm"} + 0;
1749     return eval("qq{$Lang->{Pool_Stat}}");
1750 }
1751
1752 ###########################################################################
1753 # HTML layout subroutines
1754 ###########################################################################
1755
1756 sub Header
1757 {
1758     my($title) = @_;
1759     my @adminLinks = (
1760         { link => "",                          name => $Lang->{Status},
1761                                                priv => 1},
1762         { link => "?action=summary",           name => $Lang->{PC_Summary} },
1763         { link => "?action=view&type=LOG",     name => $Lang->{LOG_file} },
1764         { link => "?action=LOGlist",           name => $Lang->{Old_LOGs} },
1765         { link => "?action=emailSummary",      name => $Lang->{Email_summary} },
1766         { link => "?action=view&type=config",  name => $Lang->{Config_file} },
1767         { link => "?action=view&type=hosts",   name => $Lang->{Hosts_file} },
1768         { link => "?action=queue",             name => $Lang->{Current_queues} },
1769         { link => "?action=view&type=docs",    name => $Lang->{Documentation},
1770                                                priv => 1},
1771         { link => "http://backuppc.sourceforge.net/faq", name => "FAQ",
1772                                                priv => 1},
1773         { link => "http://backuppc.sourceforge.net", name => "SourceForge",
1774                                                priv => 1},
1775     );
1776     print $Cgi->header();
1777     print <<EOF;
1778 <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
1779 <html><head>
1780 <title>$title</title>
1781 $Conf{CgiHeaders}
1782 </head><body bgcolor="$Conf{CgiBodyBgColor}">
1783 <table cellpadding="0" cellspacing="0" border="0">
1784 <tr valign="top"><td valign="top" bgcolor="$Conf{CgiNavBarBgColor}" width="10%">
1785 EOF
1786     NavSectionTitle("BackupPC");
1787     print "&nbsp;\n";
1788     if ( defined($In{host}) && defined($Hosts->{$In{host}}) ) {
1789         my $host = $In{host};
1790         NavSectionTitle( eval("qq{$Lang->{Host_Inhost}}") );
1791         NavSectionStart();
1792         NavLink("?host=${EscURI($host)}", $Lang->{Home});
1793         NavLink("?action=view&type=LOG&host=${EscURI($host)}", $Lang->{LOG_file});
1794         NavLink("?action=LOGlist&host=${EscURI($host)}", $Lang->{Old_LOGs});
1795         if ( -f "$TopDir/pc/$host/SmbLOG.bad"
1796                     || -f "$TopDir/pc/$host/SmbLOG.bad.z"
1797                     || -f "$TopDir/pc/$host/XferLOG.bad"
1798                     || -f "$TopDir/pc/$host/XferLOG.bad.z" ) {
1799             NavLink("?action=view&type=XferLOGbad&host=${EscURI($host)}",
1800                                 $Lang->{Last_bad_XferLOG});
1801             NavLink("?action=view&type=XferErrbad&host=${EscURI($host)}",
1802                                 $Lang->{Last_bad_XferLOG_errors_only});
1803         }
1804         if ( -f "$TopDir/pc/$host/config.pl" ) {
1805             NavLink("?action=view&type=config&host=${EscURI($host)}", $Lang->{Config_file});
1806         }
1807         NavSectionEnd();
1808     }
1809     NavSectionTitle($Lang->{Hosts});
1810     if ( defined($Hosts) && %$Hosts > 0 ) {
1811         NavSectionStart(0);
1812         foreach my $host ( GetUserHosts() ) {
1813             NavLink("?host=${EscURI($host)}", $host);
1814         }
1815         NavSectionEnd();
1816     }
1817     print <<EOF;
1818 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1819     <tr><td>$Lang->{Host_or_User_name}</td>
1820     <tr><td><form action="$MyURL" method="get"><small>
1821     <input type="text" name="host" size="10" maxlength="64">
1822     <input type="hidden" name="action" value="hostInfo"><input type="submit" value="$Lang->{Go}" name="ignore">
1823     </small></form></td></tr>
1824 </table>
1825 EOF
1826     NavSectionTitle($Lang->{NavSectionTitle_});
1827     NavSectionStart();
1828     foreach my $l ( @adminLinks ) {
1829         if ( $PrivAdmin || $l->{priv} ) {
1830             NavLink($l->{link}, $l->{name});
1831         } else {
1832             NavLink(undef, $l->{name});
1833         }
1834     }
1835     NavSectionEnd();
1836     print <<EOF;
1837 </td><td valign="top" width="5">&nbsp;&nbsp;</td>
1838 <td valign="top" width="90%">
1839 EOF
1840 }
1841
1842 sub Trailer
1843 {
1844     print <<EOF;
1845 </td></table>
1846 </body></html>
1847 EOF
1848 }
1849
1850
1851 sub NavSectionTitle
1852 {
1853     my($head) = @_;
1854     print <<EOF;
1855 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1856 <tr><td bgcolor="$Conf{CgiHeaderBgColor}"><font face="$Conf{CgiHeaderFontType}"
1857 size="$Conf{CgiHeaderFontSize}"><b>$head</b>
1858 </font></td></tr>
1859 </table>
1860 EOF
1861 }
1862
1863 sub NavSectionStart
1864 {
1865     my($padding) = @_;
1866
1867     $padding = 2 if ( !defined($padding) );
1868     print <<EOF;
1869 <table cellpadding="$padding" cellspacing="0" border="0" width="100%">
1870 EOF
1871 }
1872
1873 sub NavSectionEnd
1874 {
1875     print "</table>\n";
1876 }
1877
1878 sub NavLink
1879 {
1880     my($link, $text) = @_;
1881     print "<tr><td width=\"2%\" valign=\"top\"><b>&middot;</b></td>";
1882     if ( defined($link) ) {
1883         $link = "$MyURL$link" if ( $link eq "" || $link =~ /^\?/ );
1884         print <<EOF;
1885 <td width="98%"><a href="$link"><small>$text</small></a></td></tr>
1886 EOF
1887     } else {
1888         print <<EOF;
1889 <td width="98%"><small>$text</small></td></tr>
1890 EOF
1891     }
1892 }
1893
1894 sub h1
1895 {
1896     my($str) = @_;
1897     return \<<EOF;
1898 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1899 <tr>
1900 <td bgcolor="$Conf{CgiHeaderBgColor}">&nbsp;<font face="$Conf{CgiHeaderFontType}"
1901     size="$Conf{CgiHeaderFontSize}"><b>$str</b></font>
1902 </td></tr>
1903 </table>
1904 EOF
1905 }
1906
1907 sub h2
1908 {
1909     my($str) = @_;
1910     return \<<EOF;
1911 <table cellpadding="2" cellspacing="0" border="0" width="100%">
1912 <tr>
1913 <td bgcolor="$Conf{CgiHeaderBgColor}">&nbsp;<font face="$Conf{CgiHeaderFontType}"
1914     size="$Conf{CgiHeaderFontSize}"><b>$str</b></font>
1915 </td></tr>
1916 </table>
1917 EOF
1918 }