<?php
define('VER','3');
// ver 3: script auto-update ; firewall ; CURL
// ver 2.1: disabled notice/s    
// ver 2: support for HTTP 302
error_reporting(E_ALL ^ E_NOTICE);
define('HTTP_AGENT','');

// this is the firewall :P
$_SERVER['REMOTE_ADDR'] == gethostbyname('rejetto.com') 
    or die("you cannot call this script yourself, just report the URL to rejetto");

@chmod('.', 0755);    

function httpGet($url, $options=array()) { 
    $ch = curl_init($url);
    curl_setopt_array($ch, $options+array(CURLOPT_RETURNTRANSFER => 1));
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
} // httpGet

function httpHead($url, $options=array()) {
    $r = httpGet($url, array(CURLOPT_HEADER => 1, CURLOPT_NOBODY => 1));
    // parse header
    $a = preg_split("_\r?\n_", $r, -1, PREG_SPLIT_NO_EMPTY);
    $ret = array( '' => trim(array_shift($a)) );
    foreach ($a as $l) {
        @list($k, $l) = explode(':', $l, 2);
        $k = strtolower($k);
        $ret[$k] = (strlen($ret[$k]) ? "$ret[$k]\n" : "").trim($l);
    }    
    return $ret;
} // httpHead

$msgs = array('ver: '.VER);
function fatal($msg) { die($msg."\n".join("\n",$GLOBALS['msgs'])); }

// update attempt
$s = @httpGet('http://www.rejetto.com/hfs/synchfs.txt');
$current = join('',file($f = $_SERVER["SCRIPT_FILENAME"])); 
if (strstr($s, 'php') and $current and trim($current) != trim($s)) {    
    @chmod($f, 0777);
    if ($fh = fopen($f,'w') and fwrite($fh, $s) and fclose($fh)) {
        @chmod($f, 0755);
        fatal('updated. please recall.'); // by re-running the script now, we would get a function name clash
    }
    $msgs []= 'cannot update script';
}

$url = 'http://www.rejetto.com/files/hfs/hfs.exe';
$header = httpHead($url)
    or fatal("cannot HEAD");
!$header['location']  
    or fatal("redirection still turned on");
($size = $header['content-length']) > 10000
    or fatal("bad size");
$content = httpGet($url)
    or fatal("cannot GET");
strlen($content) == $size
    or fatal("size mismatch");
substr($content, 0, 2) == "MZ"
    or fatal("no MZ");
substr($content, -2) == "\x00\x00"
    or fatal("no 00");
// don't use file_put_contents() for PHP4, and deeper error control
$f = fopen('hfs.exe','w')
    or fatal("cannot create");
fwrite($f, $content) == $size
    or fatal("cannot write");
fclose($f)
    or fatal("cannot close");
fatal("ok");
