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