Location: PHPKode > scripts > ANDURAS SurfProtect > anduras-surfprotect/surfprot.php
<?php

// ====================================================================
// Copyright (c) 2002 by the ANDURAS AG, Passau, Germany.
// ====================================================================
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ====================================================================
// $Id: surfprot.php,v 1.21 2002/08/16 08:55:06 anders Exp $
// ====================================================================

//--------------------------------------------------------------------------
// Local the configuration defaults
//--------------------------------------------------------------------------

include_once("surfprot.defaults");

//--------------------------------------------------------------------------
// Load the virus scanner module
//--------------------------------------------------------------------------

include_once(SCANNER_INCLUDE);

//--------------------------------------------------------------------------
// Get all necessary data from server
//--------------------------------------------------------------------------

$scriptname   = $HTTP_SERVER_VARS["SCRIPT_NAME"];
$servername   = $HTTP_SERVER_VARS["SERVER_NAME"];
$user_agent   = $HTTP_SERVER_VARS["HTTP_USER_AGENT"];
$query_string = $HTTP_SERVER_VARS["QUERY_STRING"];
$scriptbase   = dirname($HTTP_SERVER_VARS["SCRIPT_NAME"]);

// formular posted?
if (isset($HTTP_POST_VARS[qurl]))
{
  $action        = $HTTP_POST_VARS["action"];
  $qurl          = $HTTP_POST_VARS["qurl"];
  $ftp_user      = $HTTP_POST_VARS["ftp_user"];
  $ftp_password  = $HTTP_POST_VARS["ftp_password"];
  $auth_user     = $HTTP_POST_VARS["auth_user"];
  $auth_password = $HTTP_POST_VARS["auth_password"];
  $remote_addr   = $HTTP_POST_VARS["remote_addr"];
  $http_referer  = $HTTP_POST_VARS["http_referer"];
}
else
{
  $action                = $HTTP_GET_VARS["action"];
  $qurl                  = $HTTP_GET_VARS["qurl"];
  $saveas                = $HTTP_GET_VARS["saveas"];
  $temp_datafile_name    = $HTTP_GET_VARS["temp_datafile_name"];
  $temp_headerfile_name  = $HTTP_GET_VARS["temp_headerfile_name"];
  $temp_scanlogfile_name = $HTTP_GET_VARS["temp_scanlogfile_name"];
  $remote_addr           = $HTTP_GET_VARS["remote_addr"];
  $http_referer          = $HTTP_GET_VARS["http_referer"];
  $retry                 = $HTTP_GET_VARS["retry"];
}

// use the quoted URL, if suppied. Otherwise take it from the query string...

unset($url);
if ($qurl != "")
  $url = urldecode($qurl);
else
  if (substr($query_string,0,5) == "url=|") $url = substr($query_string,5);

// Error, if no URL exists...
if ($url == "") die("No URL submitted....");

// if not supplied by GET/POST init with server's values
if ($remote_addr == "")
{
  if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"] != "")
    $remote_addr = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
  else
    $remote_addr = $HTTP_SERVER_VARS["REMOTE_ADDR"];
}
if ($http_referer == "")
  $http_referer = $HTTP_SERVER_VARS["HTTP_REFERER"];

// get filename of file to download
$filename = basename($url);

// calculate download timeout (make longer by each reply)
if (isset($retry) && ($retry > 0))
{
  $download_timeout = DOWNLOAD_TIMEOUT * $retry;  // or *pow(2,$retry);
  $connect_timeout = CONNECT_TIMEOUT * $retry;  // or *pow(2,$retry);
}
else
{
  $download_timeout = DOWNLOAD_TIMEOUT;
  $connect_timeout = CONNECT_TIMEOUT;
}

// set time limit of the PHP script!
if ($download_timeout == 0)
  set_time_limit(0); // no limit
else
  set_time_limit($download_timeout+10);

//--------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------

// version number

define(VERSION, "1.0");

// filename parts

define(QUARA_BEGIN, "surfprotquarantine_");
define(STORE_BEGIN, "surfprotstore_");

define(ENDING_DATA, "_data");
define(ENDING_HEADER, "_header");
define(ENDING_SCANLOG, "_scanlog");

// virus scanner return codes

define(SCANNER_NO_VIRUS_FOUND, 0);
define(SCANNER_VIRUS_FOUND, 1);
define(SCANNER_VIRUS_FOUND_AND_DISINFECTED, 2);
define(SCANNER_ERROR, 3);

//--------------------------------------------------------------------------
// Global variable
//--------------------------------------------------------------------------

// Last reported server error/errno
$server_error = "";
$server_errno = 0;

// HTTP header of download file
$header = array();

// URL of this script
$script_url  = "http://".$servername."/".$scriptname;

// file pointers of temporary files (accessed by helper-functions)
$temp_datafile_ptr = 0;
$temp_headerfile_ptr = 0;

// global variable for saving the already printed percent during download
$last_percent = 0;

// global flag for the distinguish the state of the download
$download_started = FALSE;

// Array of loaded IPs from config file
$ipconfig = array();

// Array of loaded Client patterns from config file
$agentconfig = array();

// Create filenames of temporary files if not already got from GET
if ($temp_datafile_name == "")
  $temp_datafile_name = tempnam(TEMP_DIR, "SURFPROTD");
if ($temp_headerfile_name == "")
  $temp_headerfile_name = tempnam(TEMP_DIR, "SURFPROTH");
if ($temp_scanlogfile_name == "")
  $temp_scanlogfile_name = tempnam(TEMP_DIR, "SURFPROTL");

//--------------------------------------------------------------------------
// Helper functions for determining, if connection is of type FTP 
//--------------------------------------------------------------------------

function is_ftp()
{
  global $url;
  return (strtolower(substr($url,0,6) == "ftp://"));
}

//--------------------------------------------------------------------------
// Helper functions for setting new FTP user and password
//--------------------------------------------------------------------------

function set_new_ftp_user($user, $pass)
{
  global $url;

  $up = "";
  if ($user != "") $up .= rawurlencode($user);
  if ($pass != "") $up .= ":".rawurlencode($pass);
  if ($up != "") $up .= "@";
  $rest = substr($url,strrpos($url,"@")+1);
  $url = "ftp://".$up.$rest;
}

//--------------------------------------------------------------------------
// Helper function returning, if any server error has occured
//--------------------------------------------------------------------------

function server_error_occured()
{
  global $server_errno;
  return !($server_errno < 400);
}

//--------------------------------------------------------------------------
// Helper function for reading a file into an string
//--------------------------------------------------------------------------

function read_file($filename)
{
  if (!($fd = fopen($filename, "r")))
    { echo "could not open file '$filename'"; return FALSE; }
  $contents = fread($fd, filesize($filename));
  fclose($fd);
  return $contents;
}

//--------------------------------------------------------------------------
// Load ip config file
//--------------------------------------------------------------------------

function load_config()
{
  global $ipconfig, $agentconfig;

  if (CONFIGFILE != "")
  {
    $lineno = 0;
    $list = explode("\n", read_file(CONFIGFILE));
    foreach ($list as $key => $val)
    {
      $lineno++;
      $list[$key] = trim($val);
      if ((substr($list[$key],0,1) != "#") && ($list[$key] != ""))
      {
        $entry = explode(" ", $list[$key], 2);
        $ident = strtolower(trim($entry[0]));

        if ($ident == "ip")
          $configarray = "ipconfig";
        else if ($ident == "agent")
          $configarray = "agentconfig";
        else
          die("Error in config file in line $lineno.\nExpecting 'ip' or 'client' ...");

        if ($configarray != "")
        {
          $entry2 = explode(" ", trim($entry[1]), 2);
          $what = strtolower(trim($entry2[0]));

          if ($what == "")
            die("Error in config file in line $lineno.\nExpecting <ip address> or <client pattern> ...");
          else
          {
            $options = explode(" ", trim($entry2[1]));

            foreach ($options as $val)
            {
              $val = strtolower(trim($val));
              if ($val != "")
              {
                switch ($val)
                {
                  case "transparent": ${$configarray}[$what][popup] = FALSE; break;
                  case "popup": ${$configarray}[$what][popup] = TRUE; break;
                  case "scan": ${$configarray}[$what][scan] = TRUE; break;
                  case "no_scan": ${$configarray}[$what][scan] = FALSE; break;
                  case "store_get": ${$configarray}[$what][store_get] = TRUE; break;
                  case "no_store_get": ${$configarray}[$what][store_get] = FALSE; break;
                  case "store_put": ${$configarray}[$what][store_put] = TRUE; break;
                  case "no_store_put": ${$configarray}[$what][store_put] = FALSE; break;
                  default: die("Error in config file in line $lineno.\nUnknown option '$val' ...");
                }
              }
            }
          }
        }
      }
    }
  }
}

//--------------------------------------------------------------------------
// Helper functions for the constructing the header array
//--------------------------------------------------------------------------

function add_to_header($line)
{
  global $header, $server_error, $server_errno;

  // if this is an FTP connect, interpret the FTP data
  if (is_ftp())
  {
    if (substr($line,0,4) == "213 ")
      $header['content-length'] = substr($line,4);
  }
  else
  {
    if (substr($line,0,5) == "HTTP/")
    {
      $entries = explode(" ",trim($line),3);
      $server_errno = $entries[1];
      $server_error = $entries[2];
    }

    $entries = explode(":",trim($line),2);
    if ($entries[0] != "") $header[strtolower($entries[0])] = $entries[1];
  }
}

//--------------------------------------------------------------------------
// Helper functions for download
//--------------------------------------------------------------------------

 function read_header($ch, $data)
 {
   global $temp_headerfile_ptr;

   $length = fwrite($temp_headerfile_ptr, $data);
   add_to_header($data);
   return $length;
 }

 function read_data($ch, $data)
 {
   global $temp_datafile_ptr;

   $length = fwrite($temp_datafile_ptr, $data);
   gui_scale_bar($ch);
   return $length;
 }

//--------------------------------------------------------------------------
// Download a file via CURL. Store in temporary file.
//--------------------------------------------------------------------------

function download_file($url)
{
  global $temp_datafile_ptr, $temp_datafile_name;
  global $temp_headerfile_ptr, $temp_headerfile_name;
  global $last_percent, $download_started;
  global $auth_user, $auth_password;
  global $download_timeout, $connect_timeout;

  $temp_datafile_ptr = fopen($temp_datafile_name, "w");
  $temp_headerfile_ptr = fopen($temp_headerfile_name, "w");

  $last_percent = 0;
  $download_started = FALSE;
  $error = CURLE_OK;

  // init request

  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_WRITEFUNCTION, "read_data");
  curl_setopt($ch, CURLOPT_HEADERFUNCTION, "read_header");

  // additional/optional options

  if ($download_timeout > 0)
    curl_setopt($ch, CURLOPT_TIMEOUT, $download_timeout);

  if ($connect_timeout > 0)
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);

  if (HTTP_PROXY != "")
    curl_setopt($ch, CURLOPT_PROXY, HTTP_PROXY);

  if (HTTP_PROXY_PASSWORD != "")
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, HTTP_PROXY_PASSWORD);

  if (($auth_user != "") || ($auth_password != ""))
    curl_setopt($ch, CURLOPT_USERPWD, $auth_user.":".$auth_password);

  // perform request

  if (!curl_exec($ch))
    $error = curl_errno($ch);

  curl_close($ch);

  fclose($temp_headerfile_ptr);
  fclose($temp_datafile_ptr);

  return $error;
}

//--------------------------------------------------------------------------
// Read the complete header from the file
//--------------------------------------------------------------------------

function read_header_from_file($file)
{
  global $header;

  $file_ptr = fopen($file, "r");
  while (!feof($file_ptr))
  {
    $line = fgets($file_ptr, 4096); // FIXME: be dynamic or get right max len
    add_to_header($line);
  }
  fclose($file_ptr);
}

//--------------------------------------------------------------------------
// Calculate ID for url
//--------------------------------------------------------------------------

function calc_fileid($url)
{
  return md5($url);
}

//--------------------------------------------------------------------------
// Cleanup temporary files
//--------------------------------------------------------------------------

function cleanup_temp_files()
{
  global $temp_datafile_name, $temp_headerfile_name, $temp_scanlogfile_name;

  if (file_exists($temp_datafile_name)) unlink($temp_datafile_name);
  if (file_exists($temp_headerfile_name)) unlink($temp_headerfile_name);
  if (file_exists($temp_scanlogfile_name)) unlink($temp_scanlogfile_name);
}

//--------------------------------------------------------------------------
// Cleanup storage
//--------------------------------------------------------------------------

function cleanup_storage()
{
 // delete all files older than STORAGE_AGE and start with "STORE_BEGIN"

 clearstatcache();

 $maxtime = time()-(STORAGE_AGE*60);

 $handle = opendir(STORAGE_DIR);
 while (false !== ($file = readdir($handle)))
 { 
   if (($file != ".") && ($file != "..") &&
       (substr($file, 0, strlen(STORE_BEGIN)) == STORE_BEGIN) &&
       (fileatime(STORAGE_DIR."/".$file) < $maxtime))
     @unlink(STORAGE_DIR."/".$file);
 }
 closedir($handle); 
}

//--------------------------------------------------------------------------
// Move files to storage
//--------------------------------------------------------------------------

function move_files_to_storage($url)
{
  global $temp_datafile_name, $temp_headerfile_name, $temp_scanlogfile_name;
  global $scan_enabled, $storage_put_enabled;

  if ($scan_enabled && $storage_put_enabled && (STORAGE_AGE > 0))
  {
    $id = calc_fileid($url);

    rename($temp_datafile_name, STORAGE_DIR."/".STORE_BEGIN.$id.ENDING_DATA);
    rename($temp_headerfile_name, STORAGE_DIR."/".STORE_BEGIN.$id.ENDING_HEADER);
    @unlink($temp_scanlogfile_name);
  }
}

//--------------------------------------------------------------------------
// Move files to quarantine (or just delete them)
//--------------------------------------------------------------------------

function move_files_to_quarantine($url)
{
  global $temp_datafile_name, $temp_headerfile_name, $temp_scanlogfile_name;

  if (QUARANTINE_DIR != "")
  {
    $id = calc_fileid($url);

    rename($temp_datafile_name, QUARANTINE_DIR."/".QUARA_BEGIN.$id.ENDING_DATA);
    rename($temp_headerfile_name, QUARANTINE_DIR."/".QUARA_BEGIN.$id.ENDING_HEADER);
    rename($temp_scanlogfile_name, QUARANTINE_DIR."/".QUARA_BEGIN.$id.ENDING_SCANLOG);
  }
  cleanup_temp_files();
}

//--------------------------------------------------------------------------
// Deliver complete header of download (or only the given field)
//--------------------------------------------------------------------------

function deliver_header($headerfile = "", $only = "", $skip = "")
{
  global $header, $filename, $saveas;

  // read in the header (if not already existant)
  if ((sizeof($header) == 0) && ($headerfile != "") && file_exists($headerfile))
    read_header_from_file($headerfile);

  if (is_ftp())
  {
    // Output the HTTP header suitable for a FTP download

    header("Content-type: application/octet-stream");
    header("Content-disposition: attachment; filename=".$filename);
  }
  else
  {
    // Output the original HTTP header fields
  
    foreach ($header as $field => $value)
    {
      if ((($skip == "") || ($field != $skip)) &&
          (($only == "") || ($field == $only)))
      {
        if (($field != "content-disposition") || (!$saveas))
          header($field.": ".$value);
      }
    }
  
    // add a content-disposition field, if none is supplied
  
    if ($saveas)
      header("Content-disposition: attachment; filename=".$filename);
    else if ($header["content-disposition"] == "")
      header("Content-disposition: filename=".$filename);
  }

  // Add SurfProtect headers
  header("X-Scanned-By: SurfProtect ".VERSION);
  header("X-Copyright: ANDURAS AG");
}

//--------------------------------------------------------------------------
// Deliver file for download
//--------------------------------------------------------------------------

function deliver_file($datafile)
{
  // output the data itself
  if (file_exists($datafile))
    readfile($datafile);
}

//--------------------------------------------------------------------------
// Deliver file for download
//--------------------------------------------------------------------------

function deliver_file_from_storage($id, $with_header = TRUE)
{
  // output the header first
  if ($with_header) deliver_header(STORAGE_DIR."/".STORE_BEGIN.$id.ENDING_HEADER);

  // output the data itself
  deliver_file(STORAGE_DIR."/".STORE_BEGIN.$id.ENDING_DATA);
}

//--------------------------------------------------------------------------
// Deliver file for download
//--------------------------------------------------------------------------

function deliver_downloaded_file($with_header = TRUE)
{
  global $temp_datafile_name, $temp_headerfile_name;

  // output the header first
  if ($with_header) deliver_header($temp_headerfile_name);

  // output the data itself
  deliver_file($temp_datafile_name);
}

//--------------------------------------------------------------------------
// Deliver file for download
//--------------------------------------------------------------------------

function search_in_storage($url)
{
  $id = calc_fileid($url);

  if (file_exists(STORAGE_DIR."/".STORE_BEGIN.$id.ENDING_DATA) &&
      file_exists(STORAGE_DIR."/".STORE_BEGIN.$id.ENDING_HEADER))
    return $id;
}

//--------------------------------------------------------------------------
// Scan for virus by calling the virus scanner
//--------------------------------------------------------------------------

function scan_for_virus()
{
  global $filename, $url, $remote_addr, $http_referer;

  // "call_scanner" is function of included scanner module
  $result = call_scanner();

  // add entry to surfprot log
  if (($result == SCANNER_VIRUS_FOUND) && (LOGFILE != ""))
  {
    $id = calc_fileid($url);

    $log_entry = date("Y.m.d-H.i.s").": Blocked file '$filename' (URL: $url) called from $remote_addr via $http_referer (ID: $id)";

    $fb = fopen(LOGFILE, "a");
     fwrite($fb, $log_entry."\n");
    fclose($fb);
  }

  return $result;
}

//==========================================================================
// BASIC OUTPUT FUNCTIONS
//==========================================================================

//--------------------------------------------------------------------------
// Create and return own Script URL
//--------------------------------------------------------------------------

function create_script_url($action)
{
  global $url, $script_url, $remote_addr, $http_referer, $nojavascript;
  global $temp_datafile_name, $temp_headerfile_name, $temp_scanlogfile_name;

  $myurl = $script_url;
  $myurl .= "?qurl=".urlencode($url);
  $myurl .= "&action=".$action;

  if ($temp_datafile_name != "") $myurl .= "&temp_datafile_name=".$temp_datafile_name;
  if ($temp_headerfile_name != "") $myurl .= "&temp_headerfile_name=".$temp_headerfile_name;
  if ($temp_scanlogfile_name != "") $myurl .= "&temp_scanlogfile_name=".$temp_scanlogfile_name;
  if ($remote_addr != "") $myurl .= "&remote_addr=".$remote_addr;
  if ($http_referer != "") $myurl .= "&http_referer=".$http_referer;
  if ($nojavascript) $myurl .= "&nojavascript=TRUE";

  return $myurl;
}

//--------------------------------------------------------------------------
// Download (transparent or in popup window)
//--------------------------------------------------------------------------

function download($url)
{
  global $script_url, $server_errno, $server_error;
  global $popup_enabled, $scan_enabled;

  gui_header();

  gui_download_msg();

  $result = download_file($url);

  if (server_error_occured())
  {
    if ($server_errno == 401)
      gui_auth_form();
    else if ($popup_enabled)
      gui_error_msg("ERRNO: $server_errno = $server_error");
  }
  else  // (server_errno == 0)
  {
    if ($result == CURLE_OK)
    {
      // be pessimistic as default
      $scan_result = SCANNER_ERROR;

      if ($scan_enabled)
      {
        gui_scanning_msg();
        $scan_result = scan_for_virus();

        if ($scan_result == SCANNER_VIRUS_FOUND)
        {
          // Virus found!
          move_files_to_quarantine($url);
          gui_virus_found_msg();
        }
        else if ($scan_result == SCANNER_ERROR)
        {
          // scan failure => save for analysis
          move_files_to_quarantine($url);
          gui_scan_failure_msg();
        }
        else
        {
          if ($scan_result == SCANNER_NO_VIRUS_FOUND)
            gui_no_virus_found_msg();
          else if ($scan_result == SCANNER_VIRUS_FOUND_AND_DISINFECTED)
            gui_virus_found_and_disinfected_msg();
        }
      }
      else
        gui_scan_disabled_msg();

      if (!$scan_enabled ||
          ($scan_result == SCANNER_NO_VIRUS_FOUND) ||
          ($scan_result == SCANNER_VIRUS_FOUND_AND_DISINFECTED))
      {
        if (!$popup_enabled)
        {
          // deliver directly, if PopUp has been disabled
          deliver_downloaded_file();
          move_files_to_storage($url);
        }
        else
        {
          // Deliver (indirectly) in window that has opened the popup...
          output_in_javascript_env(
           "OpenOnUnloadDisabled=1;\n".
           "opener.location='".create_script_url("deliver")."';"
          );

          // auto-closing of window enabled?
          if (POPUP_TIMEOUT != 0)
            output_in_javascript_env('setTimeout(window.close,'.POPUP_TIMEOUT.');');
        }
      }
    }
    else
    {
      // clean up if any failure occured...
      cleanup_temp_files();

      switch ($result)
      {
        case CURLE_UNSUPPORTED_PROTOCOL: // 1
          gui_error_msg("Protocol not supported.");
          break;

        case CURLE_URL_MALFORMAT: // 3
        case CURLE_URL_MALFORMAT_USER: // 4
          gui_error_msg("URL malformed.");
          break;

        case CURLE_COULDNT_RESOLVE_HOST: // 6
          gui_error_msg("Cannot resolve host (DNS problem?).");
          break;

        case CURLE_COULDNT_RESOLVE_PROXY: // 5
          gui_error_msg("Cannot resolve proxy '".HTTP_PROXY."' (DNS problem?).");
          break;

        case CURLE_COULDNT_CONNECT: // 6
          gui_error_msg("Can't connect!");
          break;
  
        case CURLE_HTTP_NOT_FOUND: // 22
          gui_error_msg("HTTP not found.");
          break;

        case CURLE_OPERATION_TIMEOUTED: // 28
          gui_timeout_msg();
          break;

        case CURLE_FTP_ACCESS_DENIED: // 9
        case CURLE_FTP_USER_PASSWORD_INCORRECT: // 10
          gui_ftp_form();
          break;

        case CURLE_FTP_WEIRD_SERVER_REPLY: // 7
        case CURLE_FTP_WEIRD_PASS_REPLY: // 11
        case CURLE_FTP_WEIRD_USER_REPLY: // 12
        case CURLE_FTP_WEIRD_PASV_REPLY: // 13
        case CURLE_FTP_WEIRD_227_FORMAT: // 14
        case CURLE_FTP_CANT_GET_HOST: // 15
        case CURLE_FTP_CANT_RECONNECT: // 16
        case CURLE_FTP_COULDNT_SET_BINARY: // 17
        case CURLE_FTP_COULDNT_RETR_FILE: // 19
        case CURLE_FTP_WRITE_ERROR: // 20
        case CURLE_FTP_QUOTE_ERROR: // 21
        case CURLE_FTP_COULDNT_STOR_FILE: // 25
        case CURLE_FTP_COULDNT_SET_ASCII: // 29
        case CURLE_FTP_PORT_FAILED: // 30
        case CURLE_FTP_COULDNT_USE_REST: // 31
        case CURLE_FTP_COULDNT_GET_SIZE: // 32
        case CURLE_FTP_BAD_DOWNLOAD_RESUME: // 36
          gui_error_msg("FTP download error");
          break;

        case CURLE_FAILED_INIT: // 2
        case CURLE_WRITE_ERROR: // 23
        case CURLE_READ_ERROR: // 26
        case CURLE_OUT_OF_MEMORY: // 27
        case CURLE_HTTP_RANGE_ERROR: // 33
        case CURLE_HTTP_POST_ERROR: // 34
          gui_error_msg("Internal CURL error No.".$result);
          break;

        case CURLE_MALFORMAT_USER: // 24
          gui_error_msg("user name is illegally specified");
          break;

        case CURLE_SSL_CONNECT_ERROR: // 35
          gui_error_msg("Could not connect to SSL.");
          break;

         // FIXME: handle this errors too...!
 
         #18) CURLE_PARTIAL_FILE
         #37) CURLE_FILE_COULDNT_READ_FILE
         #(and some more only defined in curl.h)

        default:
          gui_error_msg("Error No. $result occured!!");
          break;
      }

      flush();

    } // CURL_OK

  } // server_errno

  gui_footer();
}

//--------------------------------------------------------------------------
// download aborted action (clean-up and maybe self-closing abort window)
//--------------------------------------------------------------------------

function download_aborted()
{
  global $popup_enabled;

  cleanup_temp_files();

  if ($popup_enabled)
  {
    output_html_header();
    gui_download_aborted_msg();
    output_in_javascript_env("setTimeout(window.close,".POPUP_ABORT_TIMEOUT.");");
    output_html_footer();
  }
}

//==========================================================================
// Global signal handler (PHP >= 4.1.0)
//==========================================================================

function sig_handler($signo)
{
  download_aborted();
}

//==========================================================================
// MAIN
//==========================================================================

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Init
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

// set signal handler, if available
if (function_exists("pcntl_signal"))
{
  pcntl_signal(SIGTERM, "sig_handler");
  pcntl_signal(SIGABRT, "sig_handler");
  pcntl_signal(SIGKILL, "sig_handler");
  #pcntl_signal(SIGQUIT, "sig_handler");
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Set config based defaults
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

// read in config file, if available
load_config();

// set new default values depending on client pattern match
foreach ($agentconfig as $pattern => $val)
{
  if (ereg($pattern, $user_agent))
  {
    if (isset($agentconfig[$pattern][popup]))
      $popup_enabled = $agentconfig[$pattern][popup];

    if (isset($agentconfig[$pattern][scan]))
      $scan_enabled = $agentconfig[$pattern][scan];

    if (isset($agentconfig[$pattern][store_put]))
      $storage_put_enabled = $agentconfig[$pattern][store_put];

    if (isset($agentconfig[$pattern][store_get]))
      $storage_get_enabled = $agentconfig[$pattern][store_get];
  }
}

// set new default value depending on IP
if (isset($ipconfig[$remote_addr]))
{
  if (isset($ipconfig[$remote_addr][popup]))
    $popup_enabled = $ipconfig[$remote_addr][popup];

  if (isset($ipconfig[$remote_addr][scan]))
    $scan_enabled = $ipconfig[$remote_addr][scan];

  if (isset($ipconfig[$remote_addr][store_put]))
    $storage_put_enabled = $ipconfig[$remote_addr][store_put];

  if (isset($ipconfig[$remote_addr][store_get]))
    $storage_get_enabled = $ipconfig[$remote_addr][store_get];
}

// if falling back via meta-refresh because no javascript is available
//  => force usage of transparent mode
if (($HTTP_GET_VARS[nojavascript] == TRUE) || 
    ($HTTP_POST_VARS[nojavascript] == TRUE)) $popup_enabled = FALSE;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Set new FTP password, if new was submitted
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

// if new FTP user/password has been submitted => set it
if (isset($ftp_user))
 set_new_ftp_user($ftp_user, $ftp_password);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Check for existance in storage
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

$fileid = "";
if (($storage_get_enabled || $saveas ) && (STORAGE_AGE > 0))
{
  // cleanup the store and delete all files that are too old
  // (do this only in first stage)
  if ($action == "") cleanup_storage();

  // search in storage
  $fileid = search_in_storage($url);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Download, Scan and deliver
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

// deliver from storage, if found

if ($fileid != "")
{
  // yes, found in store => deliver directly
  deliver_file_from_storage($fileid);

  // the temp file are always generated...
  cleanup_temp_files();
}
else
{
  // no, download and scan....

  include_once("surfprot_gui.inc");

  if ($popup_enabled)
  {
    include_once("surfprot_gui_popup.inc");

    if ($action == "")
      popup();
    else if ($action == "download")
      download($url);
    else if ($action == "deliver")
    {
      deliver_downloaded_file();
      move_files_to_storage($url);
    }
    else if ($action == "stop")
      download_aborted();
  }
  else
  {
    include_once("surfprot_gui_trans.inc");
    download($url);
  }
}  
  
?>
Return current item: ANDURAS SurfProtect