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