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