#!/usr1/local/bin/perl -T
#---- uses java to generate requested images

use strict;

use FindBin;
# This fragment should be included to enable FindBin
# to be used in Taint mode.  It detaints the current
# directory available in FindBin.  It must be
# included immediately after 'use FindBin' and before
# $FindBin::Bin is invoked.
#
# Later versions of Perl do something about this automatically
# but not in the version installed at the HEASARC.
BEGIN {
    $FindBin::Bin =~ /(.*)/;
    $FindBin::Bin = $1;
}

use File::Basename;
use lib "$FindBin::Bin/cgifiles/lib";
use SkyView_Env;

my ($child, $ok);
my $maxLimit = 1200;

$ok = 0;
my $mailto="laura.m.mcdonald\@nasa.gov";  # for error notification

#------------------------------------------------------------------------
#---------------------------- limit number of simultaneous processes ----
my $rhost=$ENV{'REMOTE_ADDR'};
my $procs=`/bin/ps auxww|grep java|grep 8080|grep skyview\.jar |grep -v ps|grep -v grep|wc`;
my @xxx=split(/\s+/,$procs);
my $number= $xxx[1];
my $logfile =$ENV{LOGFILE};
#--- Taint check
if ($logfile =~ /([A-Za-z0-9.\/_]*)/) {
      $logfile = $1;  # to untaint 
} else {
   exit();
}
if ($number =~ /([0-9]*)/) {
      $number = $1;  # to untaint 
} else {
   exit();
}
if ($rhost =~ /([A-Za-z0-9.\/_\-\+]*)/) {
      $rhost = $1;  # to untaint 
} else {
   exit();
}
my $script=$ENV{'HTTP_REFERER'};
my $scriptname = basename($0);
if ($scriptname =~ /([A-Za-z0-9.\/_\-\+\:\.]*)/) {
      $scriptname = $1;  # to untaint 
} else {
   exit();
}

#--- get current time
my  @ltime=localtime(time);
my  $month=$ltime[4]+1;
my  $day=$ltime[3];
my  $year=$ltime[5]+1900;

if ($number > 20) {

   my $message= "$month/$day/$year $ltime[2]:$ltime[1]:$ltime[0]:" .
	 " Sorry, our system is overloaded with too many simultaneous ".
              "requests at this time.  Please allow time for " .
              "current requests to complete and try again.";

   my $testcmd ="echo 'runquery: too many processes($number): $rhost $month/$day/$year $ltime[2]:$ltime[1]:$ltime[0]' >>$ENV{LOGFILE}";
   system($testcmd);

print "Content-type: text/html\n\n  <br>";
print <<EOT;
<HTML>
<head><title>Too Many Processes</title>
</head>
<body bgcolor="#FFFFFF">
EOT
print <<EOT;
<h2 align="center">Too many processes</h2>
EOT

  # display an error message 
  print "<dl>\n<dd> ";
  print "$message\n"; 

print <<EOT;
<P>
<dd>If you have any questions or problems 
    please send e-mail to 
    <a href="mailto:skyview\@skyview.gsfc.nasa.gov"> 
    <tt>skyview\@skyview.gsfc.nasa.gov</tt></a>.
</dl>

<P>
<hr>
EOT

print "</body>\n</html>\n";
exit;
}
#----------------------- end: limit number of simultaneous processes ----

#--- Add number of processes to log
my $ftestcmd ="echo '\n$month/$day/$year $ltime[2]:$ltime[1]:$ltime[0]: $scriptname: $number processes: $rhost' >> $logfile";
system($ftestcmd);

my $batchset = "";
if ($0 =~ /pskcall/) {
    $batchset = "cgifiles/batch.settings";
}

#------------------------------------------------------------------------
#----------------------- query command ----------------------------------
my $javacmd = "/data/bin/java "        . 
                "-ms256m -mx1024m "               .
                "-cp $ENV{JARDIR} "               . 
                "skyview.request.CGIInitiator "   .
                "cgifiles/runtime.settings "      .
                "$batchset"                       .               
                " 2>>$ENV{LOGFILE}"; 

$|  = 1;

#--- create message that will be displayed if time limt exceeded
my $msg = <<EOT;

<b> Time limit exceeded ($maxLimit seconds) </b><br>
Either you have made too large a request (e.g., in region size or pixels),
or processing is delayed due to slow access to remote resources.<br>
Please try a smaller request.
EOT

#------------------------------------------------------------------------
#--- Error display and processing for time limit violation
sub exiter {
    print "Content-type: text/html\n\nNo content.  <br>$msg";
    my @processes = ($child);
    my $findChildren = "ps --ppid=$child";
    my @childRes = `$findChildren`;
    
    # Get rid of the header line
    shift(@childRes);
    for (@childRes) {
        my @flds = split;
        if ($flds[0] =~ /(^\d+$)/) {
          $flds[0] = $1;
	  push(@processes, $flds[0]);
        } else {
          my $tmsg ="echo '\n---runquery: proc failed taint check' >> $logfile";
          system($tmsg);
        }
    }
    sendEmail($mailto, 
           "Timeout error occurred $month/$day/$year around $ltime[2]:$ltime[1]:$ltime[0]" . ".  Check $logfile\n");

    my $stat = kill 9, @processes;
    if ($ok) {
	#print "$msg";
    } else {
	#print "Content-type: text/html\n\nNo content.  <br>$msg";
    }
    #print "<br>Killed JVM processes: @processes with return $stat\n";
    my $kmsg ="echo '\n---runquery: Time out: killed JVM processes  @processes  with stat return  of $stat' >> $logfile";
    system($kmsg);
    exit;
}

#--- set up for checking for time limit violation
#$SIG{TERM} = \&exiter;
#$SIG{PIPE} = \&exiter;
$SIG{ALRM} = \&exiter;
alarm ($maxLimit);

#--- Run query command
$child = open(IN, "$javacmd |");

#--- Send email if validation error occurs
my $inputerrorfound=0;
while (<IN>) {
    if (/irrecoverable error/) {$inputerrorfound=1;}
    if (/Reason:/ && $inputerrorfound) {
        # sendEmail($mailto, 
        #    "A validation error occurred.  Check /Apache.Logs/idl_log:\n$_");
    }
    print $_;
    $ok += 1;
}

#--- Email setup
sub sendEmail {
   my ($email,  $body) = @_;

   my $from = "SkyView.Error ";
   my $domain;
   if ($email =~ /^[^\@]+\@([^\@]+)$/) {
      $domain = $1;
   } else {
       exit();
   }

   my $mailprog = '/usr/lib/sendmail -oi';
   my $subject = "SkyView Validation Error"; 

   if ($email =~ /(\w{1}[\w-.]*)\@([\w-.]+)/) {
      $email = "$1\@$2";  # to untaint $email
   } else {
     exit();
   }
   #if (! is_tainted($email) ) {
      # Use these values to send the mail to $recipient
      open (MAIL, "|$mailprog $email") || exit();
	   
   
print MAIL	<<"MailTo";
From: $from
To: $email
Subject: $subject

$body

MailTo

close (MAIL);
exit();
}
