<?php
/*  
 * Analysis Console for Incident Databases (ACID)
 *
 * Author: Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
 *
 * Copyright (C) 2000 Carnegie Mellon University
 * (see the file 'acid_main.php' for license details)
 *
 * Purpose:   
 *
 */

function GetSensorIDs($db)
{
   $result = mysql_query("SELECT sid FROM sensor;", $db);

   while( $myrow = mysql_fetch_row($result) ) {
	$sensor_ids[] = $myrow[0];
   }

   mysql_free_result($result);

   return $sensor_ids;
}

function GetSensorName($sid, $db)
{
    $name = "";

    $temp_sql = "SELECT sid, hostname, interface, filter FROM sensor WHERE sid=".$sid;
    $tmp_result = mysql_query($temp_sql, $db);
    if ( $tmp_result )
    {
       if ( mysql_num_rows($tmp_result) > 0 )
       {
           $myrow = mysql_fetch_row($tmp_result);
           $name = $myrow[1].':'.$myrow[2];
           if ( $myrow[3] != "" )
              $name = $name.':'.$myrow[3];
       }
    }
    mysql_free_result($tmp_result);

    return $name;
}

function ErrorMessage ($message)
{
   echo '<FONT COLOR="#FF0000">'.$message.'</FONT><P>';
}

function FatalError ($message)
{
   echo '<FONT COLOR="#FF0000"><B>ACID FATAL ERROR:</B> '.$message.'</FONT>';
   die();  
}

function PrintServerInformation()
{
   echo '';
}

function PrintPageHeader()
{
     GLOBAL $PHP_SELF, $HTTP_REFERER, $QUERY_STRING,
            $HTTP_USER_AGENT, $SERVER_SOFTWARE;

     echo "<PRE>
         <B>URL:</B> '$PHP_SELF' (<B>refered by:</B> '$HTTP_REFERER')
         <B>PARAMETERS:</B> '$QUERY_STRING'
         <B>CLIENT:</B> $HTTP_USER_AGENT
         <B>SERVER:</B> $SERVER_SOFTWARE 
         </PRE>";
}

function InputSafeSQL (&$SQLstr)
/* Removes the escape sequence of \' => ' which arise when a variable containing a '-character is passed
   through a POST query.  This is needed since otherwise the MySQL parser complains */
{
   $SQLstr = str_replace("\'", "'", $SQLstr);
   $SQLstr = str_replace("\\\"", "\"", $SQLstr);
}


function PrintProtocolProfileGraphs ($db)
{
   $tcp_cnt = TCPPktCnt($db);
   $udp_cnt = UDPPktCnt($db);
   $icmp_cnt = ICMPPktCnt($db);
   $layer4_cnt = $tcp_cnt + $udp_cnt + $icmp_cnt;

   if ( $tcp_cnt > 0 )
   {  
      $tcp_percent = round($tcp_cnt/$layer4_cnt*100);
      if ( $tcp_percent == 0 )  
         $tcp_percent_show = "&lt; 1";
      else
         $tcp_percent_show = $tcp_percent; 
   }  
   else 
   {
      $tcp_percent = 0;
      $tcp_percent_show = "0";
   }

   if ( $udp_cnt > 0 )
   {  
      $udp_percent = round($udp_cnt/$layer4_cnt*100);
      if ( $udp_percent == 0 )  
         $udp_percent_show = "&lt; 1";  
      else 
         $udp_percent_show = $udp_percent;
   }   
   else
   { 
      $udp_percent = 0;
      $udp_percent_show = "0";
   }

   if ( $icmp_cnt > 0 ) 
   {
      $icmp_percent = round($icmp_cnt/$layer4_cnt*100); 
      if ( $icmp_percent == 0 )  
         $icmp_percent_show = "&lt; 1";
       else
         $icmp_percent_show = $icmp_percent;
   }
   else
   { 
      $icmp_percent = 0;
      $icmp_percent_show = 0;
   }

   if ( $tcp_percent > 0 )   $color = "#FF0000";  else  $color="#FFFFFF";
   echo '<TABLE WIDTH="100%" BORDER=0>
         <TR><TD>TCP<A HREF="acid_pkt_main.php?'.
                           'layer4=TCP&num_result_rows=-1&sort_order=time_d&submit=Query+DB">
                           ('.$tcp_percent_show.'%)</A></TD><TD></TD></TR></TABLE>
                  <TABLE WIDTH="100%" BORDER=0>
                  <TR><TD ALIGN=CENTER BGCOLOR="'.$color.'" WIDTH="'.$tcp_percent.'%">&nbsp </TD><TD></TD></TR>
                  </TABLE>';

    if ( $udp_percent > 0 )   $color = "#FF0000";  else  $color="#FFFFFF";
    echo '<TABLE WIDTH="100%" BORDER=0>
          <TR><TD>UDP<A HREF="acid_pkt_main.php?'.
                            'layer4=UDP&num_result_rows=-1&sort_order=time_d&submit=Query+DB">
                            ('.$udp_percent_show.'%)</A></TD><TD></TD></TR></TABLE>
                  <TABLE WIDTH="100%" BORDER=0>
                  <TR><TD ALIGN=CENTER BGCOLOR="'.$color.'" WIDTH="'.$udp_percent.'%">&nbsp </TD><TD></TD></TR>
                  </TABLE>';

     if ( $icmp_percent > 0 )   $color = "#FF0000";  else  $color="#FFFFFF";
     echo '<TABLE WIDTH="100%" BORDER=0>
           <TR><TD>ICMP<A HREF="acid_pkt_main.php?'.
                              'layer4=ICMP&num_result_rows=-1&sort_order=time_d&submit=Query+DB">
                              ('.$icmp_percent_show.'%)</A></TD><TD></TD></TR></TABLE>
                  <TABLE WIDTH="100%" BORDER=0>
                  <TR><TD ALIGN=CENTER BGCOLOR="'.$color.'" WIDTH="'.$icmp_percent.'%">&nbsp </TD><TD></TD></TR>
                  </TABLE>';
}

function chk_select($stored_value, $current_value)
{
     if ( $stored_value == $current_value )
          return " SELECTED";
     else
          return " ";
}

function chk_check($stored_value, $current_value)
{
     if ( $stored_value == $current_value )
          return " CHECKED";
     else
          return " ";
}

function BuildIPFormVars($ip0, $ip1, $ip2, $ip3)
{
    return ''.
    '&ip_addr%5B0%5D%5B0%5D=+&ip_addr%5B0%5D%5B1%5D=ip_src&ip_addr%5B0%5D%5B2%5D=%3D'.
    '&ip_addr%5B0%5D%5B3%5D='.$ip0.
    '&ip_addr%5B0%5D%5B4%5D='.$ip1.
    '&ip_addr%5B0%5D%5B5%5D='.$ip2. 
    '&ip_addr%5B0%5D%5B6%5D='.$ip3.
    '&ip_addr%5B0%5D%5B8%5D=+&ip_addr%5B0%5D%5B9%5D=OR'.
    '&ip_addr%5B1%5D%5B0%5D=+&ip_addr%5B1%5D%5B1%5D=ip_dst&ip_addr%5B1%5D%5B2%5D=%3D'.
    '&ip_addr%5B1%5D%5B3%5D='.$ip0.
    '&ip_addr%5B1%5D%5B4%5D='.$ip1.
    '&ip_addr%5B1%5D%5B5%5D='.$ip2.
    '&ip_addr%5B1%5D%5B6%5D='.$ip3.
    '&ip_addr%5B1%5D%5B8%5D=+&ip_addr%5B1%5D%5B9%5D=+';
}

function BuildSrcIPFormVars($ip0, $ip1, $ip2, $ip3)
{
    return ''.
    '&ip_addr%5B0%5D%5B0%5D=+&ip_addr%5B0%5D%5B1%5D=ip_src&ip_addr%5B0%5D%5B2%5D=%3D'.
    '&ip_addr%5B0%5D%5B3%5D='.$ip0.
    '&ip_addr%5B0%5D%5B4%5D='.$ip1.
    '&ip_addr%5B0%5D%5B5%5D='.$ip2. 
    '&ip_addr%5B0%5D%5B6%5D='.$ip3.
    '&ip_addr%5B0%5D%5B8%5D=+&ip_addr%5B0%5D%5B9%5D=+';
}

function BuildDstIPFormVars($ip0, $ip1, $ip2, $ip3)
{
    return ''.
    '&ip_addr%5B0%5D%5B0%5D=+&ip_addr%5B0%5D%5B1%5D=ip_dst&ip_addr%5B0%5D%5B2%5D=%3D'.
    '&ip_addr%5B0%5D%5B3%5D='.$ip0.
    '&ip_addr%5B0%5D%5B4%5D='.$ip1.
    '&ip_addr%5B0%5D%5B5%5D='.$ip2. 
    '&ip_addr%5B0%5D%5B6%5D='.$ip3.
    '&ip_addr%5B0%5D%5B8%5D=+&ip_addr%5B0%5D%5B9%5D=+';
}

function BuildUniqueAddressLink($criteria_desc, $addr_type, $criteria, $criteria_form)
{
   return '<A HREF="acid_stat_uaddr.php'.
                 '?criteria_desc='.rawurlencode($criteria_desc).
                 '&addr_type='.$addr_type.
                 '&criteria='.rawurlencode($criteria).
                 '&criteria_form='.rawurlencode($criteria_form).'">';
}

function BuildUniqueAlertLink($criteria, $criteria_desc, $criteria_form)
{
   return '<A HREF="acid_stat_alerts.php'.
                 '?criteria='.rawurlencode($criteria).
                 '&criteria_desc='.rawurlencode($criteria_desc).
                 '&criteria_form='.rawurlencode($criteria_form).'">';
}

function BuildAddressLink($ip0, $ip1, $ip2, $ip3, $netmask)
{
   return '<A HREF="acid_stat_ipaddr.php'.
                '?ip0='.$ip0.'&ip1='.$ip1.'&ip2='.$ip2.'&ip3='.$ip3.'&netmask='.$netmask.'">';
}

function AddCriteriaFormRow ( &$submit, $submit_value, &$cnt, &$current_boolean )
{
   $submit = $submit_value;

   ++$cnt;

   /* if ( $current_boolean == ' ' || $current_boolean == '' )
      $current_boolean = "OR"; */
}

function CriteriaFromSQL($criteria)
{
   /* Remove inital "SELECT ..." up to "FROM" and any trailing "ORDER BY CLAUSES */
   $t = strstr($criteria, " FROM");
   $t2 = strstr($t, " ORDER BY");
   return substr($t, 1, strlen($t) - strlen($t2));
}

function SplitCriteriaFromSQL($criteria, &$from, &$where, &$rest )
{
   /* Remove inital "SELECT ..." up to "FROM" */
   $t = strstr($criteria, "FROM");
   $where_t = strstr($t, "WHERE");
   
   /* FROM clause */
   $from = substr($t, 0, strlen($t) - strlen($where_t));

   /* find any GROUP BY, ORDER BY or LIMIT */
   $t0 = strstr($t, "GROUP BY");
   $t1 = strstr($t, "ORDER BY");
   $t2 = strstr($t, "LIMIT");

   if ( strlen($t0) > strlen($t1) && strlen($t0) > strlen($t2) )  $len = $strlen($t0);
   if ( strlen($t1) > strlen($t0) && strlen($t1) > strlen($t2) )  $len = $strlen($t1);
   if ( strlen($t2) > strlen($t0) && strlen($t2) > strlen($t1) )  $len = $strlen($t2);
  
   /* WHERE clause */
   $where = substr($where_t, 0, strlen($where_t) - $len);

   /* everything after WHERE clause */
   $rest = substr($where, strlen($where_t) - $len, $len);
}

function BuildSigLookup($signature)
/* Paul Harrington <paul@pizza.org> */
{
  $pattern=array(       "/(IDS)(\d+)/",
                                        "/(IDS)(0+)(\d+)/",
                                        "/BUGTRAQ ID (\d+)/",
                                        "/MCAFEE ID (\d+)/",
                                        "/(CVE-\d+-\d+)/");

  $replace=array("<A HREF=\"http://www.whitehats.com/\\1/\\2\" TARGET=\"_ACID_ALERT_DESC\">\\1\\2</A>",
                 "<A HREF=\"http://www.whitehats.com/\\1/\\3\" TARGET=\"_ACID_ALERT_DESC\">\\1\\2\\3</A>",
                 "<A HREF=\"http://www.securityfocus.com/bid/\\1\" TARGET=\"_ACID_ALERT_DESC\">BUGTRAQ ID \\1</A>",
                 "<A HREF=\"http://vil.nai.com/vil/dispVirus.asp?virus_k=\\1\" TARGET=\"_ACID_ALERT_DESC\">MCAFEE ID \\1</A>",
                 "<A HREF=\"http://cve.mitre.org/cgi-bin/cvename.cgi?name=\\1\" TARGET=\"_ACID_ALERT_DESC\">\\1</A>");

  return preg_replace($pattern, $replace, $signature);
}

function PrintBrowseButtons($num_result_rows, $show_rows, $max_scroll_buttons, $current_view)
{
  if ( $num_result_rows > 0 && $num_result_rows > $show_rows )
  {
     echo '
          <P><CENTER>
             <TABLE BORDER=1>
               <TR><TD ALIGN=CENTER>Query Results<BR>&nbsp'."\n";

     $tmp_num_views = ($num_result_rows / $show_rows);
     $tmp_top = $tmp_bottom = $max_scroll_buttons / 2;

     if ( ($current_view - ($max_scroll_buttons/2)) >= 0 )
        $tmp_bottom = $current_view - $max_scroll_buttons/2;
     else
        $tmp_bottom = 0;

     if ( ($current_view + ($max_scroll_buttons/2)) <= $tmp_num_views )
        $tmp_top = $current_view + $max_scroll_buttons/2;
     else
        $tmp_top = $tmp_num_views;

     /* Show a '<<' symbol of have scrolled beyond the 0 view */
     if ( $tmp_bottom != 0 )
        echo ' << ';

     for ( $i = $tmp_bottom; $i < $tmp_top; $i++)
     {
         if ( $i != $current_view )
            echo '<INPUT TYPE="submit" NAME="submit" VALUE="'.$i.'">'."\n";
         else
            echo '['.$i.'] '."\n";
     }  
     
     /* Show a '>>' symbol if last view is not visible */
     if ( ($tmp_top) < $tmp_num_views )
        echo ' >> ';

     echo '</TD></TR></TABLE></CENTER>';
  }
}


function IPProto2str($ipproto_code)
{
   switch($ipproto_code)
   {
      case 0:
          return "IP";
      case 1:
          return "ICMP";
      case 2:
          return "IGMP";
      case 4:
          return "IPIP tunnels";
      case 6:
          return "TCP";
      case 8:
          return "EGP";
      case 12:
          return "PUP";
      case  17:
          return "UDP";
      case 22:
          return "XNS UDP";
      case 29:
          return "SO TP Class 4";
      case 41:
          return "IPv6 header";
      case 43:
          return "IPv6 routing header";
      case 44:
          return "IPv6 fragmentation header";
      case 46: 
          return "RSVP";
      case 47:
          return "GRE";
      case 50: 
          return "IPSec ESP";
      case 51: 
          return "IPSec AH";
      case 58: 
          return "ICMPv6";
      case 59: 
          return "IPv6 no next header";
      case 60:
          return "IPv6 destination options";
      case 92:
          return "MTP";
      case 98:
          return "Encapsulation header";
      case 103: 
          return "PIM";
      case 108:
          return "COMP";
      case 255: 
          return "Raw IP";
      default:
          return $ipproto_code;
   }
} 

function TCPOption2str($tcpopt_code)
/* per RFC 1072, 1323, 1644 */
{
   switch($tcpopt_code)
   {
      case 2:                  /* TCPOPT_MAXSEG - maximum segment*/ 
          return "MSS";
      case 0:                  /* TCPOPT_EOL */
          return "EOL";
      case 1:                  /* TCPOPT_NOP */
          return "NOP";
      case 3:                  /* TCPOPT_WSCALE (rfc1072)- window scale factor */
          return "WS";
      case 5:                  /* TCPOPT_SACK (rfc1072)- selective ACK */
          return "SACK";
      case 4:                  /* TCPOPT_SACKOK (rfc1072)- selective ACK OK */
          return "SACKOK";
      case 6:                  /* TCPOPT_ECHO (rfc1072)- echo */
          return "Echo";
      case 7:                  /* TCPOPT_ECHOREPLY (rfc1072)- echo reply */
          return "Echo Reply";
      case 8:                  /* TCPOPT_TIMESTAMP (rfc1323)- timestamps */
          return "TS";
      case 11:                 /* TCPOPT_CC (rfc1644)- CC options */
          return "CC";
      case 12:                 /* TCPOPT_CCNEW (rfc1644)- CC options */
          return "CCNEW";
      case 13:                 /* TCPOPT_CCECHO (rfc1644)- CC options */
          return "CCECHO";
      default:
          return $tcpopt_code;
   }
}

function IPOption2str($ipopt_code)
{
   switch($ipopt_code)
   {
      case 7:              /* IPOPT_RR */
          return "RR";
      case 0:              /* IPOPT_EOL */
          return "EOL";
      case 1:              /* IPOPT_NOP */
          return "NOP";
      case 0x44:           /* IPOPT_TS */
          return "TS";
      case 0x82:           /* IPOPT_SECURITY */
          return "SEC";
      case 0x83:           /* IPOPT_LSRR */
          return "LSRR";
      case 0x84:           /* IPOPT_LSRR_E */
          return "LSRR_E";
      case 0x88:           /* IPOPT_SATID */
          return "SID";
      case 0x89:           /* IPOPT_SSRR */
          return "SSRR";
  }
}

function ICMPType2str($icmp_type)
{
  switch ($icmp_type)
  {
      case 0:                             /* ICMP_ECHOREPLY */
          return "Echo Reply";
      case 3:                             /* ICMP_DEST_UNREACH */
          return "Destination Unreachable";
      case 4:                             /* ICMP_SOURCE_QUENCH */
          return "Source Quench";
      case 5:                             /* ICMP_REDIRECT */
          return "Redirect";
      case 8:                             /* ICMP_ECHO */
          return "Echo Request";
      case 9:
          return "Router Advertisement";
      case 10:
          return "Router Solicitation"; 
      case 11:                            /* ICMP_TIME_EXCEEDED */
          return "Time Exceeded";
      case 12:                            /* ICMP_PARAMETERPROB */
          return "Parameter Problem";
      case 13:                            /* ICMP_TIMESTAMP */
          return "Timestamp Request";
      case 14:                            /* ICMP_TIMESTAMPREPLY */
          return "Timestamp Reply";
      case 15:                            /* ICMP_INFO_REQUEST */
          return "Information Request";
      case 16:                            /* ICMP_INFO_REPLY */
          return "Information Reply";
      case 17:                            /* ICMP_ADDRESS */
          return "Address Mask Request";
      case 18:                            /* ICMP_ADDRESSREPLY */
          return "Address Mask Reply";
      default:
          return $icmp_type;
  }
}

function ICMPCode2str($icmp_type, $icmp_code)
{
  if ( $icmp_type == 3 )
  {
     switch ($icmp_code)
     {
        case 0:                                    /* ICMP_NET_UNREACH */
            return "Network Unreachable";
        case 1:                                    /* ICMP_HOST_UNREACH */
            return "Host Unreachable";
        case 2:                                    /* ICMP_PROT_UNREACH */
            return "Protocol Unreachable";
        case 3:                                    /* ICMP_PORT_UNREACH */
            return "Port Unreachable";
        case 4:                                    /* ICMP_FRAG_NEEDED */
            return "Fragmentation Needed/DF set";
        case 5:                                    /* ICMP_SR_FAILED */
            return "Source Route failed";
        case 6:                                    /* ICMP_NET_UNKNOWN */
            return "Network Unknown";
        case 7:                                    /* ICMP_HOST_UNKNOWN */
            return "Host Unknown";
        case 8:                                    /* ICMP_HOST_ISOLATED */
            return "Host Isolated";
        case 9:                                    /* ICMP_NET_ANO */
            return "Network ANO";
        case 10:                                   /* ICMP_HOST_ANO */
            return "Host ANO";
        case 11:                                   /* ICMP_NET_UNR_TOS */
            return "Network Unreach TOS";
        case 12:                                   /* ICMP_HOST_UNR_TOS */
            return "Host Unreach TOS";
        case 13:                                   /* ICMP_PKT_FILTERED */
            return "Packet Filtered";
        case 14:                                   /* ICMP_PREC_VIOLATION */
            return "Precedence violation";
        case 15:                                   /* ICMP_PREC_CUTOFF */
            return "Precedence cut off";
        default:
            return $icmp_code;
     }
  }
  else
     return $icmp_code;
}

function PrintPayloadChar( $char )
{
   if ( $char >= 32 && $char <= 127 )
      echo htmlspecialchars(chr($char));
   else
      echo '.';
}

function PrintBase64PacketPayload ( $encoded_payload )
{
     /* strip out the <CR> at the end of each block */
     $encoded_payload = str_replace("\n", "", $encoded_payload);
     //printf(" len = %d\n", strlen($encoded_payload));
     //printf("%s \n", $encoded_payload);

     $payload = base64_decode($encoded_payload);
     $len = strlen($payload);
     printf(" length = %s\n", strlen($payload));

     for ($i = 0; $i < strlen($payload); $i++ )
     {
          if ( $i % 16 == 0 )
          {
             /* dump the ASCII characters */
             if ( $i != 0 )
             {
                echo '  ';
                for ($j = $i-16; $j < $i; $j++ )
                   PrintPayloadChar($payload[$j]);
             }
             printf("\n%03x : ", $i);
          }

          printf("%s ", bin2hex($payload[$i]) );
     }

     /* print the remained of any ASCII chars */
     if ( ($i % 16) != 0 )
     {
        for ( $j = 0; $j < 16 - ($i % 16); $j++)
            echo '   ';

        echo '  ';
        
        for ( $j = $len - ($i % 16); $j < $len; $j++ )
           PrintPayloadChar($payload[$j]);
     }
}

function PrintAsciiPacketPayload ( $encoded_payload )
{
   echo $encoded_payload;
}

function PrintHexPacketPayload ( $encoded_payload )
{
     /* strip out the <CR> at the end of each block */
     $encoded_payload = str_replace("\n", "", $encoded_payload);
     $payload = $encoded_payload;

     $len = strlen($payload);
     printf(" length = %s\n", strlen($payload)/2);

     for ($i = 0; $i < strlen($payload); $i += 2 )
     {
          if ( $i % 32 == 0 )
          {
             /* dump the ASCII characters */
             if ( $i != 0 )
             {
                echo '  ';
                for ($j = $i-32; $j < $i; $j+=2 )
                {
                    $t = hexdec($payload[$j].$payload[$j+1]);
                    PrintPayloadChar($t);
                }
             }
             printf("\n%03x : ", $i/2);
          }
          printf("%s%s ", $payload[$i], $payload[$i+1] );
     }

     /* space through to align end of hex dump */
     if ( $i % 32 )
        for ( $j = 0; $j < 32 - ($i % 32); $j+=2)
           echo '   ';

     echo '  ';

     /* print the ASCII decode */
     if ( $i % 32 )
        $start = $len - ($i % 32);
     else
        $start = $len - 32;

     for ( $j = $start; $j < $i; $j+=2 )
     {
        $t = hexdec($payload[$j].$payload[$j+1]);
        PrintPayloadChar($t);
     } 
}

function PrintPacketPayload($data, $encode_type)
{
     printf("\n<PRE>\n");

     /* print the packet based on encoding type */;
     if ( $encode_type == "1" )
         PrintBase64PacketPayload($data);
     else if ($encode_type == "2" )
         PrintAsciiPacketPayload($data);  
     else if ($encode_type == "0" )
         PrintHexPacketPayload($data); 

     printf("\n</PRE>\n");
}

function PrintPacketLookupBrowseButtons($seq, $save_sql, $db)
{

  $result2 = mysql_query($save_sql, $db);
  $myrow2 = mysql_fetch_row($result2);
  $num_rows = mysql_num_rows($result2);


  echo '<CENTER><FONT>
         <B>Packet '.($seq+1).' of '.$num_rows.'</B><BR>';
  if ( $seq > 0 )
  {
     mysql_data_seek($result2, $seq-1);
     $myrow2 = mysql_fetch_row($result2);
     echo '<INPUT TYPE="submit" NAME="submit" VALUE="<< Previous #'.($seq-1).'-('.$myrow2[0].'-'.$myrow2[1].')">';
  }
  else
  {
     echo '[ First ]';
  }

  echo '&nbsp&nbsp&nbsp';
  if ( $seq < $num_rows-1 )
  {
     mysql_data_seek($result2, $seq+1);
     $myrow2 = mysql_fetch_row($result2);
     echo '<INPUT TYPE="submit" NAME="submit" VALUE=">> Next #'.($seq+1).'-('.$myrow2[0].'-'.$myrow2[1].')">';
  }
  else
  {
     echo '[ Last ]';
  }
  
  echo '</FONT></CENTER>';

  mysql_free_result($result2);
}

function GetQueryResultID($submit, &$seq, &$sid, &$cid)
{
  /* extract the sid and cid from the $submit variable of the form
     #XX-(XX-XX) 
      |   |  |
      |   |  |--- cid
      |   |------ sid
      |---------- sequence number of DB lookup
  */
  strtok($submit, "#");
  $seq = strtok("-");
         strtok("(");
  $sid = strtok("-");
  $cid = strtok(")");
}

function PacketLookup($submit, $db, $save_sql, $mod_snort_config)
{
  GLOBAL $action, $ag_add_key;

  GetQueryResultID($submit, $seq, $sid, $cid);

  PrintPacketLookupBrowseButtons($seq, $save_sql, $db);
  echo '<HR>';

  /* Event */
  $sql2 = "SELECT signature, timestamp FROM event WHERE sid='".$sid."' AND cid='".$cid."'";
  $result2 = mysql_query($sql2, $db);
  $myrow2 = mysql_fetch_row($result2);

  if ( $myrow2[0] == "" )
  {
     echo '<CENTER><B>';
     ErrorMessage("Alert DELETED");
     echo '</CENTER></B>';
  }

  echo '
       <TABLE BORDER=1>
          <TR><TD CLASS="metatitle" WIDTH=50 ALIGN=CENTER ROWSPAN=3>Meta
              <TD>
                  <TABLE BORDER=1 CELLPADDING=4>
                    <TR><TD CLASS="plfieldhdr" >ID #</TD>
                        <TD CLASS="plfieldhdr">Time</TD>
                        <TD CLASS="plfieldhdr">Triggered Signature</TD></TR>
                    <TR><TD CLASS="plfield">'.($sid." - ".$cid).'</TD>
                        <TD CLASS="plfield">'.$myrow2[1].'</TD>
                        <TD CLASS="plfield">'.BuildSigLookup($myrow2[0]).'</TD></TR>      
                  </TABLE>
              </TD>
           </TR>';

  $sql4 = "SELECT hostname, interface, filter FROM sensor  WHERE sid='".$sid."'";
  $result4 = mysql_query($sql4, $db);
  $myrow4 = mysql_fetch_row($result4);

  echo '  <TR>
             <TD>
                <TABLE BORDER=1 CELLPADDING=4>
                  <TR><TD CLASS="metatitle" ALIGN=CENTER ROWSPAN=2>Sensor</TD>
                       <TD class="plfieldhdr">name</TD>
                       <TD class="plfieldhdr">interface</TD>
                       <TD class="plfieldhdr">filter</TD>
                  </TR>
                  <TR><TD class="plfield">'.$myrow4[0].'</TD>
                      <TD class="plfield">'.$myrow4[1].'</TD>
                      <TD class="plfield">'.
                      ( ($myrow4[2] == "") ? "&nbsp;<I>none</I>&nbsp;" : $myrow4[2] ).'</TD>
                  </TR>
                 </TABLE>     
          </TR>';
  mysql_free_result($result4);

  $sql4 = "SELECT DISTINCTROW acid_ag_alert.ag_id, ag_name, ag_desc ".
          "FROM acid_ag_alert LEFT JOIN acid_ag ON acid_ag_alert.ag_id = acid_ag.ag_id ".
          "WHERE ag_sid=".$sid." AND ag_cid=".$cid;
  $result4 = mysql_query($sql4, $db);
  $num = mysql_num_rows($result4);

  echo ' <TR>
           <TD>
             <TABLE BORDER=1 CELLPADDING=4>
               <TR><TD CLASS="metatitle" ALIGN=CENTER ROWSPAN='.($num+1).'>Alert<BR>Group</TD>';
  
  if ( $num > 0 )
     echo '        <TD class="plfieldhdr">ID #</TD>
                   <TD class="plfieldhdr">Name</TD>
                   <TD class="plfieldhdr">Description</TD></TR>';  
  else
     echo '        <TD>&nbsp;&nbsp;<I>none</I>&nbsp;</TD></TR>';

  for ($i = 0; $i < $num; $i++)
  {
     $myrow4 = mysql_fetch_row($result4);

     echo '    <TR><TD class="plfield">'.$myrow4[0].'</TD>
                   <TD class="plfield">'.$myrow4[1].'</TD>
                   <TD class="plfield">'.$myrow4[2].'</TD>
               </TR>';
  }
  echo '      </TABLE>';
  mysql_free_result($result4);

  echo '   </TR>
        </TABLE>';
  mysql_free_result($result2);

  /* IP */
  $sql2 = "SELECT ip_src0, ip_src1, ip_src2, ip_src3, ip_dst0, ip_dst1, ip_dst2, ip_dst3, ".
          "ip_ver, ip_hlen, ip_tos, ip_len, ip_id, ip_flags, ip_off, ip_ttl, ip_csum, ip_proto". 
          " FROM iphdr  WHERE sid='".$sid."' AND cid='".$cid."'";

  $result2 = mysql_query($sql2, $db);
  $myrow2 = mysql_fetch_row($result2);

  if ( $myrow2[0] != "" )
  {
  $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='0'";
  $result3 = mysql_query($sql3, $db);
  $num_opt = mysql_num_rows($result3);

  echo '
       <TABLE BORDER=1>
          <TR><TD CLASS="iptitle" WIDTH=50 ROWSPAN=3 ALIGN=CENTER>IP';
  echo '      <TD>';
  echo '         <TABLE BORDER=1 CELLPADDING=2>';
  echo '            <TR><TD class="plfieldhdr">source addr</TD>
                        <TD class="plfieldhdr">&nbsp dest addr &nbsp</TD>
                        <TD class="plfieldhdr">Ver</TD>
                        <TD class="plfieldhdr">Hdr Len</TD>
                        <TD class="plfieldhdr">TOS</TD>
                        <TD class="plfieldhdr">length</TD>
                        <TD class="plfieldhdr">ID</TD>
                        <TD class="plfieldhdr">flags</TD>
                        <TD class="plfieldhdr">offset</TD>
                        <TD class="plfieldhdr">TTL</TD>
                        <TD class="plfieldhdr">chksum</TD></TR>';
  echo '             <TR><TD class="plfield">
                       <A HREF="acid_stat_ipaddr.php?'.
                               'ip0='.$myrow2[0].'&ip1='.$myrow2[1].'&ip2='.$myrow2[2].'&ip3='.$myrow2[3].
                               '&netmask=32">'.
                            $myrow2[0].".".$myrow2[1].".".$myrow2[2].".".$myrow2[3].'</A></TD>';
  echo '                 <TD class="plfield">
                         <A HREF="acid_stat_ipaddr.php?'.
                                 'ip0='.$myrow2[4].'&ip1='.$myrow2[5].'&ip2='.$myrow2[6].'&ip3='.$myrow2[7].
                                 '&netmask=32">'.
                                 $myrow2[4].".".$myrow2[5].".".$myrow2[6].".".$myrow2[7].'</A></TD>';
  echo '                 <TD class="plfield">'.$myrow2[8].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[9].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[10].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[11].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[12].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[13].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[14].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[15].'</TD>';
  echo '                 <TD class="plfield">'.$myrow2[16].'</TD></TR>';
  echo '         </TABLE>';

  echo '  <TR>
             <TD>
                <TABLE BORDER=1 CELLPADDING=4>
                  <TR><TD CLASS="iptitle" ALIGN=CENTER ROWSPAN=2>FQDN</TD>
                       <TD class="plfieldhdr">Source Name</TD>
                       <TD class="plfieldhdr">Dest. Name</TD>
                  </TR>
                  <TR><TD class="plfield">'.
                      (gethostbyaddr($myrow2[0].'.'.$myrow2[1].'.'.$myrow2[2].'.'.$myrow2[3])).'</TD>
                      <TD class="plfield">'.
                      (gethostbyaddr($myrow2[4].'.'.$myrow2[5].'.'.$myrow2[6].'.'.$myrow2[7])).'</TD>
                  </TR>
                 </TABLE>     
          </TR>';

  echo '  <TR>';
  echo '      <TD>';
  echo '         <TABLE BORDER=1 CELLPADDING=4>';
  echo '           <TR><TD CLASS="iptitle" ALIGN=CENTER ROWSPAN='.(($num_opt != 0) ? ($num_opt+1) : 1).'>Options</TD>';

  $layer4_proto = $myrow2[17];

  if ( $num_opt != 0)
  {
     echo '            <TD></TD>
                       <TD class="plfieldhdr">code</TD>
                       <TD class="plfieldhdr">length</TD>
                       <TD class="plfieldhdr" ALIGN=CENTER>data</TD>';

     for ( $i = 0; $i < $num_opt; $i++)
     {
         $myrow3 = mysql_fetch_row($result3);
         echo '    <TR><TD>#'.($i+1).'</TD>';
         echo '        <TD class="plfield">'.IPOption2str($myrow3[4]).'</TD>';
         echo '        <TD class="plfield">'.$myrow3[5].'</TD>';
         echo '        <TD class="plfield">'.$myrow3[6].'</TD></TR>';             
     }
   }
   else
   {
     echo '             <TD> &nbsp&nbsp&nbsp <I>none </I></TD></TR>';
   }
      echo '         </TABLE></TD></TR>';  
                       

  echo '</TABLE>';
  mysql_free_result($result3);
  }
  mysql_free_result($result2);

  /* TCP */
  if ( $layer4_proto == "6" )  
  {
     $sql2 = "SELECT tcp_sport, tcp_dport, tcp_seq, tcp_ack, tcp_off, tcp_res, tcp_flags, tcp_win, ".
             "       tcp_csum, tcp_urp FROM tcphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
     $result2 = mysql_query($sql2, $db);
     $myrow2 = mysql_fetch_row($result2);

     $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='6'";
     $result3 = mysql_query($sql3, $db);
     $num_opt = mysql_num_rows($result3);

      echo '
           <TABLE BORDER=1>
              <TR><TD CLASS="layer4title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>TCP';
      echo '      <TD>';
      echo '         <TABLE BORDER=1 CELLPADDING=2>';
      echo '            <TR><TD class="plfieldhdr">source<BR> port</TD>
                            <TD class="plfieldhdr"> dest<BR> &nbsp port &nbsp</TD>
                            <TD class="plfieldhdr">R<BR>1</TD>
                            <TD class="plfieldhdr">R<BR>0</TD>
                            <TD class="plfieldhdr">U<BR>R<BR>G</TD>
                            <TD class="plfieldhdr">A<BR>C<BR>K</TD>
                            <TD class="plfieldhdr">P<BR>S<BR>H</TD>
                            <TD class="plfieldhdr">R<BR>S<BR>T</TD>
                            <TD class="plfieldhdr">S<BR>Y<BR>N</TD>
                            <TD class="plfieldhdr">F<BR>I<BR>N</TD>
                            <TD class="plfieldhdr">seq #</TD>
                            <TD class="plfieldhdr">ack</TD>
                            <TD class="plfieldhdr">offset</TD>
                            <TD class="plfieldhdr">res</TD>
                            <TD class="plfieldhdr">window</TD>
                            <TD class="plfieldhdr">urp</TD>
                            <TD class="plfieldhdr">chksum</TD></TR>';
      echo '            <TR><TD class="plfield">'.$myrow2[0].'</TD>';
      echo '                <TD class="plfield">'.$myrow2[1].'</TD>';
      echo '                <TD class="plfield">';
      if ( ($myrow2[6] & 128) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 64 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 32) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 16 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 8) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 4 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 2 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="plfield">';
      if ( ($myrow2[6] & 1 ) != 0 )
           echo 'X';
      echo '                    </TD>';
     
      echo '                <TD class="plfield">'.$myrow2[2].'</TD>';    
      echo '                <TD class="plfield">'.$myrow2[3].'</TD>';
      echo '                <TD class="plfield">'.$myrow2[4].'</TD>';
      echo '                <TD class="plfield">'.$myrow2[5].'</TD>';
      echo '                <TD class="plfield">'.$myrow2[7].'</TD>';
      echo '                <TD class="plfield">'.$myrow2[9].'</TD>';
      echo '                <TD class="plfield">'.$myrow2[8].'</TD></TR>';
      echo '         </TABLE></TR></TR>';
      echo '  <TR>';
      echo '      <TD>';
      echo '         <TABLE BORDER=1 CELLPADDING=4>';
      echo '           <TR><TD CLASS="layer4title" ALIGN=CENTER ROWSPAN='.(($num_opt != 0) ? ($num_opt+1) : 1).'>Options</TD>';

      if ( $num_opt != 0)
      {
         echo '            <TD></TD>
                           <TD class="plfieldhdr">code</TD>
                           <TD class="plfieldhdr">length</TD>
                           <TD class="plfieldhdr">data</TD>';

         for ( $i = 0; $i < $num_opt; $i++)
         {
             $myrow3 = mysql_fetch_row($result3);
             echo '    <TR><TD class="plfield">#'.($i+1).'</TD>';
             echo '        <TD class="plfield">'.TCPOption2str($myrow3[4]).'</TD>';
             echo '        <TD class="plfield">'.$myrow3[5].'</TD>';
             echo '        <TD class="plfield">'.$myrow3[6].'</TD></TR>';             
         }
      }
      else
      {
         echo '             <TD class="plfield"> &nbsp&nbsp&nbsp <I>none </I></TD></TR>';
      }
      echo '         </TABLE></TD></TR>';                       

      echo '</TABLE>';

      mysql_free_result($result2);
      mysql_free_result($result3);
  }

  /* UDP */
  if ( $layer4_proto == "17" )
  {

     $sql2 = "SELECT * FROM udphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
     $result2 = mysql_query($sql2, $db);
     $myrow2 = mysql_fetch_row($result2);

     echo '
           <TABLE BORDER=1>
              <TR><TD CLASS="layer4title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>UDP</TD>';
     echo '      <TD>';
     echo '         <TABLE BORDER=1 CELLPADDING=2>';
     echo '            <TR><TD class="plfieldhdr">source port</TD>
                            <TD class="plfieldhdr">dest port</TD>
                            <TD class="plfieldhdr">length</TD></TR>';
     echo '            <TR><TD class="plfield">'.$myrow2[2].'</TD>';
     echo '                <TD class="plfield">'.$myrow2[3].'</TD>';
     echo '                <TD class="plfield">'.$myrow2[4].'</TD></TR>';
     echo '         </TABLE></TD></TR>';
     echo '</TABLE>';

     mysql_free_result($result2);
  }

  /* ICMP */
  if ( $layer4_proto == "1" )
  {
     $sql2 = "SELECT icmp_type, icmp_code, icmp_csum, icmp_id, icmp_seq FROM icmphdr ".
             "WHERE sid='".$sid."' AND cid='".$cid."'";
     $result2 = mysql_query($sql2, $db);
     $myrow2 = mysql_fetch_row($result2);

     echo '
           <TABLE BORDER=1>
              <TR><TD class="layer4title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>ICMP';
     echo '      <TD>';
     echo '         <TABLE BORDER=1 CELLPADDING=2>';
     echo '            <TR><TD class="plfieldhdr">type</TD>
                           <TD class="plfieldhdr">code</TD>
                           <TD class="plfieldhdr">checksum</TD>
                           <TD class="plfieldhdr">id</TD>
                           <TD class="plfieldhdr">seq #</TR>';
     echo '            <TR><TD class="plfield">'.ICMPType2str($myrow2[0]).'</TD>';
     echo '                <TD class="plfield">'.ICMPCode2str($myrow2[0],$myrow2[1]).'</TD>';
     echo '                <TD class="plfield">'.$myrow2[2].'</TD>';
     echo '                <TD class="plfield">'.$myrow2[3].'</TD>';
     echo '                <TD class="plfield">'.$myrow2[4].'</TD></TR>';
     echo '         </TABLE>';
     echo '</TABLE>';

     mysql_free_result($result2);
  }

  /* Print the Payload */
  $sql2 = "SELECT data_payload FROM data WHERE sid='".$sid."' AND cid='".$cid."'";
  $result2 = mysql_query($sql2, $db);

  /* get encoding information and detail_level on the payload */
  $sql3 = 'SELECT encoding, detail FROM sensor WHERE sid='.$sid;
  $result3 = mysql_query($sql3, $db);
   $myrow3 = mysql_fetch_row($result3);  
  
  echo '
        <TABLE BORDER=1>
           <TR><TD class="payloadtitle" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>Payload';
  echo '       <TD>';

  if ( mysql_num_rows($result2) != 0 )
  {
     $myrow2 = mysql_fetch_row($result2);

     /* print the packet based on encoding type */
     PrintPacketPayload($myrow2[0], $myrow3[0]);

     mysql_free_result($result3);     
  }
  else
  {
     /* Don't have payload so lets print out why by checking the detail level */

     /* if have fast detail level */
     if ( $myrow[1] == "0" )
        echo '<BR> &nbsp <I>Fast logging used so payload was discarded </I><BR>';
     else
        echo '<BR> &nbsp <I>none </I><BR>';
  }
  echo '</TABLE><P>';

  mysql_free_result($result2);

  PrintPacketLookupBrowseButtons($seq, $save_sql, $db);

  PrintQueryResultAction($action, $ag_add_key, 1);  
}

function EmailPacketLookup($submit, $db, $save_sql, $mod_snort_config)
{
/* Author: Steve Halligan <geek2@geeksquad.com
*  Based on function PacketLookup.  Removed links to other data that wont work in an email.  Removed raw html to enable output buffer to collect the output.
*/
  GLOBAL $action, $ag_add_key;

  GetQueryResultID($submit, $seq, $sid, $cid);

  echo '<HR>';

  /* Event */
  $sql2 = "SELECT signature, timestamp FROM event WHERE sid='".$sid."' AND cid='".$cid."'";
  $result2 = mysql_query($sql2, $db);
  $myrow2 = mysql_fetch_row($result2);

  if ( $myrow2[0] == "" )
  {
     echo '<CENTER><B>';
     ErrorMessage("Alert DELETED");
     echo '</CENTER></B>';
  }

  echo '
       <TABLE BORDER=1>
          <TR><TD CLASS="meta_title" WIDTH=50 ALIGN=CENTER ROWSPAN=3>Meta
              <TD>
                  <TABLE BORDER=1 CELLPADDING=4>
                    <TR><TD CLASS="pl_fieldhdr" >ID #</TD>
                        <TD CLASS="pl_fieldhdr">Time</TD>
                        <TD CLASS="pl_fieldhdr">Triggered Signature</TD></TR>
                    <TR><TD CLASS="pl_field">'.($sid." - ".$cid).'</TD>
                        <TD CLASS="pl_field">'.$myrow2[1].'</TD>
                        <TD CLASS="pl_field">'.BuildSigLookup($myrow2[0]).'</TD></TR>      
                  </TABLE>
              </TD>
           </TR>';

  $sql4 = "SELECT hostname, interface, filter FROM sensor  WHERE sid='".$sid."'";
  $result4 = mysql_query($sql4, $db);
  $myrow4 = mysql_fetch_row($result4);

  echo '  <TR>
             <TD>
                <TABLE BORDER=1 CELLPADDING=4>
                  <TR><TD CLASS="meta_title" ALIGN=CENTER ROWSPAN=2>Sensor</TD>
                       <TD class="pl_fieldhdr">name</TD>
                       <TD class="pl_fieldhdr">interface</TD>
                       <TD class="pl_fieldhdr">filter</TD>
                  </TR>
                  <TR><TD class="pl_field">'.$myrow4[0].'</TD>
                      <TD class="pl_field">'.$myrow4[1].'</TD>
                      <TD class="pl_field">'.
                      ( ($myrow4[2] == "") ? "&nbsp;<I>none</I>&nbsp;" : $myrow4[2] ).'</TD>
                  </TR>
                 </TABLE>     
          </TR>';
  mysql_free_result($result4);

  echo '   </TR>
        </TABLE>';
  mysql_free_result($result2);

  /* IP */
  $sql2 = "SELECT ip_src0, ip_src1, ip_src2, ip_src3, ip_dst0, ip_dst1, ip_dst2, ip_dst3, ".
          "ip_ver, ip_hlen, ip_tos, ip_len, ip_id, ip_flags, ip_off, ip_ttl, ip_csum, ip_proto". 
          " FROM iphdr  WHERE sid='".$sid."' AND cid='".$cid."'";

  $result2 = mysql_query($sql2, $db);
  $myrow2 = mysql_fetch_row($result2);

  $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='0'";
  $result3 = mysql_query($sql3, $db);
  $num_opt = mysql_num_rows($result3);

  echo '
       <TABLE BORDER=1>
          <TR><TD CLASS="ip_title" WIDTH=50 ROWSPAN=3 ALIGN=CENTER>IP';
  echo '      <TD>';
  echo '         <TABLE BORDER=1 CELLPADDING=2>';
  echo '            <TR><TD class="pl_fieldhdr">source addr</TD>
                        <TD class="pl_fieldhdr">&nbsp dest addr &nbsp</TD>
                        <TD class="pl_fieldhdr">Ver</TD>
                        <TD class="pl_fieldhdr">Hdr Len</TD>
                        <TD class="pl_fieldhdr">TOS</TD>
                        <TD class="pl_fieldhdr">length</TD>
                        <TD class="pl_fieldhdr">ID</TD>
                        <TD class="pl_fieldhdr">flags</TD>
                        <TD class="pl_fieldhdr">offset</TD>
                        <TD class="pl_fieldhdr">TTL</TD>
                        <TD class="pl_fieldhdr">chksum</TD></TR>';
  echo '             <TR><TD class="pl_field">'.$myrow2[0].".".$myrow2[1].".".$myrow2[2].".".$myrow2[3].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[4].".".$myrow2[5].".".$myrow2[6].".".$myrow2[7].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[8].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[9].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[10].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[11].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[12].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[13].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[14].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[15].'</TD>';
  echo '                 <TD class="pl_field">'.$myrow2[16].'</TD></TR>';
  echo '         </TABLE>';

  echo '  <TR>
             <TD>
                <TABLE BORDER=1 CELLPADDING=4>
                  <TR><TD CLASS="ip_title" ALIGN=CENTER ROWSPAN=2>FQDN</TD>
                       <TD class="pl_fieldhdr">Source Name</TD>
                       <TD class="pl_fieldhdr">Dest. Name</TD>
                  </TR>
                  <TR><TD class="pl_field">'.
                      (gethostbyaddr($myrow2[0].'.'.$myrow2[1].'.'.$myrow2[2].'.'.$myrow2[3])).'</TD>
                      <TD class="pl_field">'.
                      (gethostbyaddr($myrow2[4].'.'.$myrow2[5].'.'.$myrow2[6].'.'.$myrow2[7])).'</TD>
                  </TR>
                 </TABLE>     
          </TR>';

  echo '  <TR>';
  echo '      <TD>';
  echo '         <TABLE BORDER=1 CELLPADDING=4>';
  echo '           <TR><TD CLASS="ip_title" ALIGN=CENTER ROWSPAN='.(($num_opt != 0) ? ($num_opt+1) : 1).'>Options</TD>';

  $layer4_proto = $myrow2[17];

  if ( $num_opt != 0)
  {
     echo '            <TD></TD>
                       <TD class="pl_fieldhdr">code</TD>
                       <TD class="pl_fieldhdr">length</TD>
                       <TD class="pl_fieldhdr" ALIGN=CENTER>data</TD>';

     for ( $i = 0; $i < $num_opt; $i++)
     {
         $myrow3 = mysql_fetch_row($result3);
         echo '    <TR><TD>#'.($i+1).'</TD>';
         echo '        <TD class="pl_field">'.IPOption2str($myrow3[4]).'</TD>';
         echo '        <TD class="pl_field">'.$myrow3[5].'</TD>';
         echo '        <TD class="pl_field">'.$myrow3[6].'</TD></TR>';             
     }
   }
   else
   {
     echo '             <TD> &nbsp&nbsp&nbsp <I>none </I></TD></TR>';
   }
      echo '         </TABLE></TD></TR>';  
                       

  echo '</TABLE>';

  mysql_free_result($result2);
  mysql_free_result($result3);

  /* TCP */
  if ( $layer4_proto == "6" )  
  {
     $sql2 = "SELECT tcp_sport, tcp_dport, tcp_seq, tcp_ack, tcp_off, tcp_res, tcp_flags, tcp_win, ".
             "       tcp_csum, tcp_urp FROM tcphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
     $result2 = mysql_query($sql2, $db);
     $myrow2 = mysql_fetch_row($result2);

     $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='6'";
     $result3 = mysql_query($sql3, $db);
     $num_opt = mysql_num_rows($result3);

      echo '
           <TABLE BORDER=1>
              <TR><TD CLASS="layer4_title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>TCP';
      echo '      <TD>';
      echo '         <TABLE BORDER=1 CELLPADDING=2>';
      echo '            <TR><TD class="pl_fieldhdr">source<BR> port</TD>
                            <TD class="pl_fieldhdr"> dest<BR> &nbsp port &nbsp</TD>
                            <TD class="pl_fieldhdr">R<BR>1</TD>
                            <TD class="pl_fieldhdr">R<BR>0</TD>
                            <TD class="pl_fieldhdr">U<BR>R<BR>G</TD>
                            <TD class="pl_fieldhdr">A<BR>C<BR>K</TD>
                            <TD class="pl_fieldhdr">P<BR>S<BR>H</TD>
                            <TD class="pl_fieldhdr">R<BR>S<BR>T</TD>
                            <TD class="pl_fieldhdr">S<BR>Y<BR>N</TD>
                            <TD class="pl_fieldhdr">F<BR>I<BR>N</TD>
                            <TD class="pl_fieldhdr">seq #</TD>
                            <TD class="pl_fieldhdr">ack</TD>
                            <TD class="pl_fieldhdr">offset</TD>
                            <TD class="pl_fieldhdr">res</TD>
                            <TD class="pl_fieldhdr">window</TD>
                            <TD class="pl_fieldhdr">urp</TD>
                            <TD class="pl_fieldhdr">chksum</TD></TR>';
      echo '            <TR><TD class="pl_field">'.$myrow2[0].'</TD>';
      echo '                <TD class="pl_field">'.$myrow2[1].'</TD>';
      echo '                <TD class="pl_field">';
      if ( ($myrow2[6] & 128) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 64 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 32) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 16 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 8) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 4 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 2 ) != 0 )
           echo 'X';
      echo '                    </TD><TD class="pl_field">';
      if ( ($myrow2[6] & 1 ) != 0 )
           echo 'X';
      echo '                    </TD>';
     
      echo '                <TD class="pl_field">'.$myrow2[2].'</TD>';    
      echo '                <TD class="pl_field">'.$myrow2[3].'</TD>';
      echo '                <TD class="pl_field">'.$myrow2[4].'</TD>';
      echo '                <TD class="pl_field">'.$myrow2[5].'</TD>';
      echo '                <TD class="pl_field">'.$myrow2[7].'</TD>';
      echo '                <TD class="pl_field">'.$myrow2[9].'</TD>';
      echo '                <TD class="pl_field">'.$myrow2[8].'</TD></TR>';
      echo '         </TABLE></TR></TR>';
      echo '  <TR>';
      echo '      <TD>';
      echo '         <TABLE BORDER=1 CELLPADDING=4>';
      echo '           <TR><TD CLASS="layer4_title" ALIGN=CENTER ROWSPAN='.(($num_opt != 0) ? ($num_opt+1) : 1).'>Options</TD>';

      if ( $num_opt != 0)
      {
         echo '            <TD></TD>
                           <TD class="pl_fieldhdr">code</TD>
                           <TD class="pl_fieldhdr">length</TD>
                           <TD class="pl_fieldhdr">data</TD>';

         for ( $i = 0; $i < $num_opt; $i++)
         {
             $myrow3 = mysql_fetch_row($result3);
             echo '    <TR><TD class="pl_field">#'.($i+1).'</TD>';
             echo '        <TD class="pl_field">'.TCPOption2str($myrow3[4]).'</TD>';
             echo '        <TD class="pl_field">'.$myrow3[5].'</TD>';
             echo '        <TD class="pl_field">'.$myrow3[6].'</TD></TR>';             
         }
      }
      else
      {
         echo '             <TD class="pl_field"> &nbsp&nbsp&nbsp <I>none </I></TD></TR>';
      }
      echo '         </TABLE></TD></TR>';                       

      echo '</TABLE>';

      mysql_free_result($result2);
      mysql_free_result($result3);
  }

  /* UDP */
  if ( $layer4_proto == "17" )
  {

     $sql2 = "SELECT * FROM udphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
     $result2 = mysql_query($sql2, $db);
     $myrow2 = mysql_fetch_row($result2);

     echo '
           <TABLE BORDER=1>
              <TR><TD CLASS="layer4_title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>UDP</TD>';
     echo '      <TD>';
     echo '         <TABLE BORDER=1 CELLPADDING=2>';
     echo '            <TR><TD class="pl_fieldhdr">source port</TD>
                            <TD class="pl_fieldhdr">dest port</TD>
                            <TD class="pl_fieldhdr">length</TD></TR>';
     echo '            <TR><TD class="pl_field">'.$myrow2[2].'</TD>';
     echo '                <TD class="pl_field">'.$myrow2[3].'</TD>';
     echo '                <TD class="pl_field">'.$myrow2[4].'</TD></TR>';
     echo '         </TABLE></TD></TR>';
     echo '</TABLE>';

     mysql_free_result($result2);
  }

  /* ICMP */
  if ( $layer4_proto == "1" )
  {
     $sql2 = "SELECT icmp_type, icmp_code, icmp_csum, icmp_id, icmp_seq FROM icmphdr ".
             "WHERE sid='".$sid."' AND cid='".$cid."'";
     $result2 = mysql_query($sql2, $db);
     $myrow2 = mysql_fetch_row($result2);

     echo '
           <TABLE BORDER=1>
              <TR><TD class="layer4_title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>ICMP';
     echo '      <TD>';
     echo '         <TABLE BORDER=1 CELLPADDING=2>';
     echo '            <TR><TD class="pl_fieldhdr">type</TD>
                           <TD class="pl_fieldhdr">code</TD>
                           <TD class="pl_fieldhdr">checksum</TD>
                           <TD class="pl_fieldhdr">id</TD>
                           <TD class="pl_fieldhdr">seq #</TR>';
     echo '            <TR><TD class="pl_field">'.ICMPType2str($myrow2[0]).'</TD>';
     echo '                <TD class="pl_field">'.ICMPCode2str($myrow2[0],$myrow2[1]).'</TD>';
     echo '                <TD class="pl_field">'.$myrow2[2].'</TD>';
     echo '                <TD class="pl_field">'.$myrow2[3].'</TD>';
     echo '                <TD class="pl_field">'.$myrow2[4].'</TD></TR>';
     echo '         </TABLE>';
     echo '</TABLE>';

     mysql_free_result($result2);
  }

  /* Print the Payload */
  $sql2 = "SELECT data_payload FROM data WHERE sid='".$sid."' AND cid='".$cid."'";
  $result2 = mysql_query($sql2, $db);

  /* get encoding information and detail_level on the payload */
  $sql3 = 'SELECT encoding, detail FROM sensor WHERE sid='.$sid;
  print ($sql3);
  $result3 = mysql_query($sql3, $db);
   $myrow3 = mysql_fetch_row($result3);  
  
  echo '
        <TABLE BORDER=1>
           <TR><TD class="payload_title" WIDTH=50 ROWSPAN=2 ALIGN=CENTER>Payload';
  echo '       <TD>';

  if ( mysql_num_rows($result2) != 0 )
  {
     $myrow2 = mysql_fetch_row($result2);

     /* print the packet based on encoding type */
     PrintPacketPayload($myrow2[0], $myrow3[0]);

     mysql_free_result($result3);     
  }
  else
  {
     /* Don't have payload so lets print out why by checking the detail level */

     /* if have fast detail level */
     if ( $myrow[1] == "0" )
        echo '<BR> &nbsp <I>Fast logging used so payload was discarded </I><BR>';
     else
        echo '<BR> &nbsp <I>none </I><BR>';
  }
  echo '</TABLE><P>';

  mysql_free_result($result2);

  
}

function PrintFreshPage($refresh_stat_page, $stat_page_refresh_time)
{
   if ( $refresh_stat_page )
      echo '<META HTTP-EQUIV="REFRESH" CONTENT="'.$stat_page_refresh_time.';">';
}

?>



















