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