Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
All torrents is red
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / General / General Chat

2022-10-06 18:54:44
this is weird seedbox cant get error but client can

the big issue is finding cause i had a quick look through my announce which has debug and is much faster then the v3 this will return any code issues bit of a long shot

if error change define('DEBUG', true); to false
true writes a log file to root false returns error to client
this announce is independent with only two functions

announce.php - add db details
<?php
// DB Details
define("DB_HOST", "localhost");
define("DB_USER", "dbusername");
define("DB_PASS", "dbpassword");
define("DB_NAME", "dbname");
define('DB_CHAR', 'utf8mb4');
// Debug, true - log exception OR false - simple error to client
define('DEBUG', true);
// Debug - Allow Browsers  (NEVER USE ON LIVE SITE, FOR TESTING ONLY)
define('PRINT_DEBUG', false);

// 1st Fuction PDO Prepared Statement & DEBUG
function pdo($pdo, $sql, $args = NULL, $message = 'Strange Error')
{
   try {
       if (!$args) {
           return $pdo->query($sql);
       }
       $stmt = $pdo->prepare($sql);
       $stmt->execute($args);
       return $stmt;
   } catch (\Exception $e) {
       if (DEBUG) {
           throw $e;
       } else {
           die(response($message));
       }
   }
}

// 2nd Fuction Response To Client
function response($peer_array, $seeders = 0, $leechers = 0)
{
   if (is_string($peer_array)) {
       return 'd14:failure reason' . strlen($peer_array) . ':' . $peer_array . 'e';
   }
   $peer_list = '';
   foreach ($peer_array as $peer) {
       $pid = '';
       if (!isset($_GET['no_peer_id'])) {
           $real_id = hex2bin($peer[2]);
           $pid = '7:peer id' . strlen($real_id) . ':' . $real_id;
       }
       $peer_list .= 'd2:ip' . strlen($peer[0]) . ':' . $peer[0] . $pid . '4:porti' . $peer[1] . 'ee';
   }
   $response = 'd8:intervali60e12:min intervali30e8:completei' . $seeders . 'e10:incompletei' . $leechers . 'e5:peersl' . $peer_list . 'ee';
   return $response;
}

// Set Database Connection
$opt = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
   PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
   $pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
   die(response('The Database Details Are Incorrect'));
}

// Register custom exception handler
if (DEBUG) {
   include "exception_helper.php";
   set_exception_handler("handleUncaughtException");
}

// Block Browsers
$agent = $_SERVER["HTTP_USER_AGENT"] ?? 'n/a';
if (!PRINT_DEBUG && preg_match("/^Mozilla|^Opera|^Links|^Lynx/i", $agent)) {
   die('What Are you doing ???');
}

// Block Unwanted Clients
//$stmt = pdo($pdo, "SELECT code FROM clients", null, 'Error in agent select')->fetchAll();
//$users_agent = substr($_GET['peer_id'], 0, 8);
//foreach ($stmt as $bannedclient) {
//    if (@strpos($users_agent, $bannedclient['code']) !== false) {
//        die(response('Client is banned'));
//    }
//}

// Needed Fields
foreach (['info_hash', 'peer_id', 'port', 'uploaded', 'downloaded', 'left'] as $key) {
   $client[$key] = $_GET[$key];
   if (!isset($client[$key])) {
       die(response("missing key $key"));
   }
}
// Check info_hash & peer_id correct
foreach (["info_hash", "peer_id"] as $key) {
   if (strlen($client[$key]) != 20) {
       die(response("short peer_id or hash"));
   }
}
// Check Correct Values
foreach (['uploaded', 'downloaded', 'left'] as $key) {
   if (!is_numeric($client[$key]) || $client[$key] < 0) {
       die(response("wierd number"));
   }
}

foreach (['event'] as $key) {
   $client[$key] = $_GET[$key];
}
// Check Event
if (!in_array(strtolower($client['event']), ['started', 'completed', 'stopped', ''])) {
   die(response("no event"));
}
// Check Port
if (!ctype_digit($client['port']) || $client['port'] < 1 || $client['port'] > 65535) {
   die(response('Invalid client port'));
}
// Check IP
$client['ip'] = $_SERVER["REMOTE_ADDR"] ?? $_GET['ip'];
// bin2hex info_hash
$client['info_hash'] = bin2hex($client['info_hash']);
// bin2hex peer_id
$client['peer_id'] = bin2hex($client['peer_id']);
// Check 20 Byte Hex String
if (strlen($client['info_hash']) != 40) {
   die(response("Invalid info hash hex value."));
} elseif (strlen($client['peer_id']) != 40) {
   die(response("Invalid peer id hex value."));
}

$client['passkey'] = $_GET['passkey'];
if (empty($client['passkey'])) {
   die(response("no passkey"));
} elseif (strlen($client['passkey']) != 32) {
   die(response("Invalid passkey (" . strlen($client['passkey']) . " - $client[passkey])"));
}

$client['seeder'] = ($client['left'] == 0) ? "yes" : "no";

// Get User
$user = array();
$stmt = pdo($pdo, "SELECT u.id, u.class, u.uploaded, u.downloaded, u.enabled, u.status, u.ip, u.passkey FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? LIMIT 1", [$client['passkey']], 'Error getting user')->fetch(PDO::FETCH_ASSOC);
foreach ($stmt as $key => $value) {
   $user[$key] = $value;
}
//$role = $user['group_role_id'];
//$permission = pdo($pdo, "SELECT permission_id, can_download FROM `permissions` WHERE `permission_id`=?",  [$role], 'Error getting user permission')->fetch(PDO::FETCH_ASSOC);
//foreach ($permission as $key => $value) {
//    $user[$key] = $value;
//}

// Check User
if (!$user) {
   die(response("Cannot locate a user with that passkey!"));
//} elseif ($user["can_download"] == "no") {
//    die(response("You do not have permission to download."));
} elseif (!$user["passkey"] == $client['passkey']) {
   die(response("Can NOT find user passkey."));
} elseif (!$user["enabled"] == 'yes') {
   die(response("not enabled."));
} elseif (!$user["status"] == 'confirmed') {
   die(response("status not confirmed."));
}

// Get Torrent
$torrent = pdo($pdo,  "SELECT id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed FROM torrents WHERE info_hash=?", [$client['info_hash']], 'error getting torrent')->fetch(PDO::FETCH_ASSOC);

// Check Torrent
if (!$torrent) {
   die(response("Torrent not found on this hash = $client[info_hash]"));
} elseif ($torrent["banned"] == 'yes') {
   die(response("Torrent has been banned - hash = $client[info_hash]"));
}

// Get Peer
$peer = pdo($pdo, "SELECT seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey FROM peers WHERE torrent = ? AND peer_id = ? AND passkey = ?", [$torrent['id'], $client['peer_id'], $client['passkey']], 'Error getting user peer')->fetch(PDO::FETCH_ASSOC);

if (!$peer) {
   // New Peer
   //$countslot = pdo($pdo, "SELECT DISTINCT torrent FROM peers WHERE userid =? AND seeder=?", [$user['id'], 'no'], 'Error getting user slots')->rowCount();
   //if ($slot >= $user['maxslots']) {
   //    die(response("Maximum Slot exceeded! You may only download $slot torrent at a time."));
   //}
   pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client)VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ['yes', $torrent['id'], $client['peer_id'], $client['ip'], $client['passkey'], $client['port'], $client['uploaded'], $client['downloaded'], $client['left'], gmdate("Y-m-d H:i:s"), gmdate("Y-m-d H:i:s"), $client['seeder'], $user['id'], $agent], 'Error getting inserting peer');
   //pdo($pdo, "INSERT INTO `snatched` (`uid`, `tid`, `start_time`, `upload_time`, `completed`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `upload_time` = ?", [$user['id'], $torrent['id'], strtotime(gmdate("Y-m-d H:i:s")), strtotime(gmdate("Y-m-d H:i:s")), $client['seeder'], gmdate("Y-m-d H:i:s")], 'Error getting inserting snatched');
} else {
   // Update Peer
   $elapsed = ($peer['seeder'] == 'yes') ? 600 - floor(($peer['ez'] - time()) / 60) : 0;
   $upthis = max(0, $client['uploaded'] - $peer["uploaded"]);
   $downthis = max(0, $client['downloaded'] - $peer["downloaded"]); // $downthis = $user['class'] == _VIP ? 0 : max(0, $client['downloaded'] - $peer["downloaded"]);
   if ($upthis > 0 || $downthis > 0 || $elapsed > 0) {
       if ($torrent["freeleech"] == 1) {
           pdo($pdo, "UPDATE users SET uploaded = uploaded + ? WHERE id=?", [$upthis, $userid], 'Error getting updating user');
           //pdo($pdo,  "UPDATE LOW_PRIORITY `snatched` SET `upload` = `upload` + '$upthis', `upload_time` = '" . strtotime(gmdate("Y-m-d H:i:s")) . "', `last_time` = `last_time` + '$elapsed', completed = ? WHERE `tid` = ? AND `uid` = ?", [$client['seeder'], $torrent['id'], $user['id']], 'Error getting updating snatched');
       } else {
           pdo($pdo, "UPDATE users SET uploaded = uploaded + ?, downloaded = downloaded + ? WHERE id=?", [$upthis, $downthis, $user['id']], 'Error getting updating snatched');
           //pdo($pdo, "UPDATE LOW_PRIORITY `snatched` SET `upload` = `upload` + '$upthis', `download` = `download` + '$downthis', `upload_time` = '" . strtotime(gmdate("Y-m-d H:i:s")) . "', `last_time` = `last_time` + '$elapsed', completed = ? WHERE `tid` = ? AND `uid` = ?", [$client['seeder'], $torrent['id'], $user['id']], 'Error getting updating snatched');
       }
   }
   pdo($pdo, "UPDATE peers SET ip = ?, passkey = ?, port = ?, uploaded = ?, downloaded = ?, to_go = ?, last_action = ?, client = ?, seeder = ? WHERE torrent = ? AND peer_id = ?", [$client['ip'], $client['passkey'], $client['port'], $client['uploaded'], $client['downloaded'], $client['left'], gmdate("Y-m-d H:i:s"), $agent, $client['seeder'], $torrent['id'], $client['peer_id']], 'Error getting updating peer');
}

// Event Completed
if ($client['event'] == "completed") {
   pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES (?,?,?) ON DUPLICATE KEY UPDATE date = ?", [$user['id'], $torrent['id'], gmdate("Y-m-d H:i:s"), gmdate("Y-m-d H:i:s")], 'Error getting inserting completed');
   //pdo($pdo, "UPDATE `snatched`  SET `completed` = ? WHERE `tid` = ? AND `uid` = ?", [1, $torrent['id'], $user['id']], 'Error snatched complete');
   $torrent['times_completed']++;
}

// Event Stopped Delete & Return Empty Response
if ($client['event'] == "stopped") {
   pdo($pdo, "DELETE FROM peers  WHERE  torrent = ? AND peer_id = ?", [$torrent['id'], $client['peer_id']], 'Error getting updating peer');
   //die(response(array(), 0, 0));
}

// Get Peers For Response
$all_peers = pdo($pdo, "SELECT peer_id, ip, port, seeder  FROM peers  WHERE torrent = ?", [$torrent['id']], 'Error getting all peers')->fetchAll();
$response_array = array();
$seeders = 0;
$leechers = 0;
foreach ($all_peers as $peer) {
   if ($peer['seeder'] == 'no') {
       $leechers++;
   } else {
       $seeders++;
   }
   $response_array[] = array($peer['ip'], $peer['port'], $peer['peer_id']);
}

// Update Torrent
if ($torrent["banned"] != "yes") {
   pdo($pdo, "UPDATE torrents SET last_action = ?, leechers = ?, seeders = ?, times_completed = ?, visible = ? WHERE id=?", [gmdate("Y-m-d H:i:s"), $leechers, $seeders, $torrent['times_completed'], 'yes', $torrent['id']], 'Error getting all peers');
}

// Show Response
die(response($response_array, $seeders, $leechers));


add exception_helper.php to root
<?php
//start add 19.01.2020 DrTech76, Exception handler verbose output
/**
* Prepares verbose output of the debug backtrace, for inclusion in trace and debug outputs and logging
* Parameters:
* @param backtrace - the output of a call to debug_backtrace() function
* @param depth - How many levels back to read the traces for
* Returns:
* @return string
**/

function get_verbose_backtrace($backtrace = null, $depth = 0)
{
   $skipFirst = false;
   $output = array();
   if (!(isset($depth) and is_numeric($depth))) { //no limit
       $depth = 0;
   } else {
       $depth = intval($depth);
   }

   if (!(isset($backtrace) and is_array($backtrace))) {
       if (function_exists("ReflectionFunction")) {
           $dbtRef = new ReflectionFunction("debug_backtrace");
           if ($dbtRef->getNumberOfParameters() == 2) {
               $backtrace = debug_backtrace(true, $depth);
           } else {
               $backtrace = debug_backtrace();
           }
       } else {
           $backtrace = debug_backtrace();
       }

       $skipFirst = true; //the first item will be this function so skip accordingly
   }

   foreach ($backtrace as $currDepth => $trace) {
       if ($skipFirst === true and $currDepth === 0) {
           continue;
       }

       if (!(isset($trace["file"]) or isset($trace["function"]))) {
           continue;
       }

       $isObject = (isset($trace["class"]));
       $function = $trace["function"];

       //$output[]="Function: ReflectionMethod exists ".var_export(function_exists("ReflectionMethod"),true);
       //$output[]="Function: ReflectionFunction exists ".var_export(function_exists("ReflectionFunction"),true);
       if ($isObject === true) {
           if (function_exists("ReflectionMethod")) {
               $funcParamsRef = new ReflectionMethod($trace["class"], $trace["function"]);
           }
           $function = $trace['class'] . $trace['type'] . $function;
       } else {
           if (function_exists("ReflectionFunction")) {
               $funcParamsRef = new ReflectionFunction($trace["function"]);
           }
       }

       $currTrace = "\n[" . $currDepth . "] File: " . ((isset($trace["file"])) ? $trace["file"] : "Undefined") . " Line: " . ((isset($trace["line"])) ? $trace["line"] : "Undefined");
       $currTrace .= "\nFunction: " . $function;
       if (isset($trace["args"])) {
           $currTrace .= "\nCall parameters";

           if (isset($funcParamsRef)) {
               $funcParams = $funcParamsRef->getParameters();
               foreach ($funcParams as $fpIndex => $funcParam) {
                   $currTrace .= "\nParam: " . $funcParam["name"] . " Passed value: " . ((isset($trace["args"][$fpIndex])) ? var_export($trace["args"][$fpIndex], true) : "[Not passed]: " . (($funcParam->isDefaultValueAvailable() === true) ? "[Using the Default value]" . var_export($funcParam->getDefaultValue(), true) : "[No Default value is available]"));
               }
           } else {
               foreach ($trace["args"] as $fpIndex => $funcParam) {
                   $currTrace .= "\nParam[" . $fpIndex . "]: Passed value: " . var_export($trace["args"][$fpIndex], true);
               }
           }
       }

       $output[] = $currTrace;
   }

   if (count($output) > 0) {
       $output = array_merge(array("Call Stack"), $output);
   }

   return join("\n", $output);
}

// Debug Complex Exception Log & Redirect
function handleUncaughtException($e)
{
   // Construct the error string
   $error = "\nUncaught Exception: " . ($message = date("Y-m-d H:i:s - "));
   $error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n";
   // Add verbose trace and debug output
   $error .= "\n" . get_verbose_backtrace($e->getTrace());
   // Log details of error in a file
   error_log($error, 3, "exception_log.txt");
   //autolink(URLROOT, Lang::T("OOPS_ERR"));
}
Last edited by M-jay warn on 2022-10-06 19:48:56
2022-10-07 09:42:11
I forgot one thing to ask you M-jay,
I use Cloudflare and there it is selected that TLS 1.3 is default and I read what HDVinnie wrote on one of github:

https://github.com/rakshasa/rtorrent/issues/964

so as i don't have much knowledge about this can only read but not act properly due to my "ignorance" of the subject

PS
Please don't take "ignorance" the wrong way I can't find the right words for this description


www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
2022-10-07 16:31:04
"Lack of troubleshooting skills on this script" is correct, but we never think about that because we love to help. Who really knows the most? Impossible.

Are you still having issues? I looked over the script yesterday and I see a lot of old stock code, and nothing stood out in the way of attention so if it worked before, then I would rely on  it now. It must be a port issue in your internal network configuration.
2022-10-07 17:05:15
"Lack of debugging ability" might be a partially correct expression mate, but doesn't matter we know what the purpose of it is.

Right now I'm having problems with the domain because it's being moved to OVHCloud but it will probably be the same when I reinstall the script. Had a massive ddos attack on 4 occasions during the day and had to put the server in "rescue mode"

All my firewall's are turned off and it's the same on my test trackers V2 and V3


www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
2022-10-09 07:57:18
Thanks @STorrents2020

I'm back on rails and tracker working after my transfer to OVH and I still have the same problem.

How to fix that "portproblem"




Thanks

PS

Installed TBDV on the same server and same seedbox to seed it without problem and torrent is green all time


www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
Last edited by Botanicar on 2022-10-09 19:36:34
2022-10-10 10:09:25
that most mean its bad code in TT

is this the announce you use from tbdev
https://github.com/Hect0rius/TorrentBits/blob/master/announce.php

if so at top you see require_once('include/mysql.php'); and you can use TT with that announce
just replace this on line 450
finishedat  with last_action
and include the mysql.php file maybe change location and link to file to backend/mysql.php

i would try that so you dont lose all your work

also running for some time on tbdev on new install after while might go red again but at least we are getting close

I will spend time reading the tbdev announce
Last edited by M-jay warn on 2022-10-10 10:22:28
2022-10-10 12:58:17
No mate, that announce don't work

This one working OK:



<?php
/*
+------------------------------------------------
|   TBDev.net BitTorrent Tracker PHP
|   =============================================
|   by CoLdFuSiOn
|   (c) 2003 - 2011 TBDev.Net
|   http://www.tbdev.net
|   =============================================
|   svn: http://sourceforge.net/projects/tbdevnet/
|   Licence Info: GPL
+------------------------------------------------
|   $Date$
|   $Revision$
|   $Author$
|   $URL$
+------------------------------------------------
*/error_reporting(0);
////////////////// GLOBAL VARIABLES ////////////////////////////
$TBDEV['baseurl'] = 'https://youpage.com';
$TBDEV['announce_interval'] = 60 * 30;
$TBDEV['user_ratios'] = 0;
$TBDEV['connectable_check'] = 0;
define ('UC_VIP', 2);
// DB setup
$TBDEV['mysql_host'] = "localhost";
$TBDEV['mysql_user'] = "db_usernam";
$TBDEV['mysql_pass'] = "db_password";
$TBDEV['mysql_db']   = "db_name";
////////////////// GLOBAL VARIABLES ////////////////////////////

// DO NOT EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING!!

define( 'TIME_NOW', time() );

$agent = $_SERVER["HTTP_USER_AGENT"];

// Deny access made with a browser...
if (
   preg_match('%^Mozilla/|^Opera/|^Links |^Lynx/%i', $agent) ||
   isset($_SERVER['HTTP_COOKIE']) ||
   isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ||
   isset($_SERVER['HTTP_ACCEPT_CHARSET'])
   )
   err("torrent not registered with this tracker CODE 1");

if( !$_GET['compact'] )
 {
   err('Sorry, this tracker no longer supports non-compact clients!');
 }
/////////////////////// FUNCTION DEFS ///////////////////////////////////
function dbconn()
{
   global $TBDEV;

   if (!@mysql_connect($TBDEV['mysql_host'], $TBDEV['mysql_user'], $TBDEV['mysql_pass']))
   {
 err('Please call back later');
   }
   mysql_select_db($TBDEV['mysql_db']) or err('Please call back later');
}

function err($msg)
{
benc_resp(array('failure reason' => array('type' => 'string', 'value' => $msg)));

exit();
}

function benc_resp($d)
{
benc_resp_raw(benc(array('type' => 'dictionary', 'value' => $d)));
}

function benc_resp_raw($x)
{
   header( "Content-Type: text/plain" );
   header( "Pragma: no-cache" );

   if ( $_SERVER['HTTP_ACCEPT_ENCODING'] == 'gzip' )
   {
       header( "Content-Encoding: gzip" );
       echo gzencode( $x, 9, FORCE_GZIP );
   }
   else
       echo $x ;
}

function benc($obj) {
if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"]))
return;
$c = $obj["value"];
switch ($obj["type"]) {
case "string":
return benc_str($c);
case "integer":
return benc_int($c);
case "list":
return benc_list($c);
case "dictionary":
return benc_dict($c);
default:
return;
}
}

function benc_str($s) {
return strlen($s) . ":$s";
}

function benc_int($i) {
return "i" . $i . "e";
}

function benc_list($a) {
$s = "l";
foreach ($a as $e) {
$s .= benc($e);
}
$s .= "e";
return $s;
}

function benc_dict($d) {
$s = "d";
$keys = array_keys($d);
sort($keys);
foreach ($keys as $k) {
$v = $d[$k];
$s .= benc_str($k);
$s .= benc($v);
}
$s .= "e";
return $s;
}

function hash_where($name, $hash) {
   $shhash = preg_replace('/ *$/s', "", $hash);
   return "($name = " . sqlesc($hash) . " OR $name = " . sqlesc($shhash) . ")";
}

function sqlesc($x) {
   return "'".mysql_real_escape_string($x)."'";
}

function portblacklisted($port)
{
// direct connect
if ($port >= 411 && $port <= 413) return true;

// bittorrent
if ($port >= 6881 && $port <= 6889) return true;

// kazaa
if ($port == 1214) return true;

// gnutella
if ($port >= 6346 && $port <= 6347) return true;

// emule
if ($port == 4662) return true;

// winmx
if ($port == 6699) return true;

return false;
}
/////////////////////// FUNCTION DEFS END ///////////////////////////////

$parts = array();
if( !isset($_GET['passkey']) OR !preg_match('/^[0-9a-fA-F]{32}$/i', $_GET['passkey'], $parts) )
err("Invalid Passkey");
else
$GLOBALS['passkey'] = $parts[0];

foreach (array("info_hash","peer_id","event","ip","localip") as $x)
{
if(isset($_GET["$x"]))
$GLOBALS[$x] = "" . $_GET[$x];
}

foreach (array("port","downloaded","uploaded","left") as $x)
{
$GLOBALS[$x] = 0 + $_GET[$x];
}


foreach (array("passkey","info_hash","peer_id","port","downloaded","uploaded","left") as $x)

if (!isset($x)) err("Missing key: $x");



foreach (array("info_hash","peer_id") as $x)

if (strlen($GLOBALS[$x]) != 20) err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");

unset($x);

$info_hash = bin2hex($info_hash);

$ip = $_SERVER['REMOTE_ADDR'];

$port = 0 + $port;
$downloaded = 0 + $downloaded;
$uploaded = 0 + $uploaded;
$left = 0 + $left;

$rsize = 30;
foreach(array("num want", "numwant", "num_want") as $k)
{
if (isset($_GET[$k]))
{
$rsize = (int)$_GET[$k];
break;
}
}


if (!$port || $port > 0xffff)
err("invalid port");

if (!isset($event))
$event = "";

$seeder = ($left == 0) ? "yes" : "no";

dbconn();


$user_query = mysql_query("SELECT id, uploaded, downloaded, class, enabled FROM users WHERE passkey=".sqlesc($passkey)) or err("Tracker error 2");

if ( mysql_num_rows($user_query) != 1 )

err("Unknown passkey. Please redownload the torrent from {$TBDEV['baseurl']}.");

$user = mysql_fetch_assoc($user_query);
if( $user['enabled'] == 'no' ) err('Permission denied, you\'re not enabled');


$res = mysql_query("SELECT id, banned, seeders + leechers AS numpeers, added AS ts FROM torrents WHERE info_hash = " .sqlesc($info_hash));//" . hash_where("info_hash", $info_hash));

$torrent = mysql_fetch_assoc($res);
if (!$torrent)
err("torrent not registered with this tracker CODE 2");

$torrentid = $torrent["id"];

$fields = "seeder, peer_id, compact, ip, port, uploaded, downloaded, userid";

//$numpeers = $torrent["numpeers"];
 $limit = "";

 if ($torrent['numpeers'] > $rsize)
   $limit = "ORDER BY RAND() LIMIT $rsize";
   
 $whereap ='';
 
 if ($seeder == 'yes')
   $whereap = "AND seeder = 'no'";
   
 $res = mysql_query("SELECT $fields FROM peers WHERE torrent = $torrentid AND connectable = 'yes' {$whereap} {$limit}");
 
 unset($whereap);
 
//////////////////// START NEW COMPACT MODE/////////////////////////////

 $resp = "d" . benc_str("interval") . "i" . $TBDEV['announce_interval'] ."e" . benc_str("min interval") . "i" . 300 ."e5:"."peers" ;

 $peers = '';

 $peer_num = 0;
 
 while ($row = mysql_fetch_assoc($res))
 {
   $peers .= $row['compact']; //pack('Nn', ip2long($row['ip']), $row['port']);

   $peer_num++;
 }



$resp .= strlen($peers) . ':' . $peers . 'e';



$selfwhere = "torrent = $torrentid AND " . hash_where("peer_id", $peer_id);

///////////////////////////// END NEW COMPACT MODE////////////////////////////////



if (!isset($self))
{
$res = mysql_query("SELECT $fields FROM peers WHERE $selfwhere");
$row = mysql_fetch_assoc($res);
if ($row)
{
$userid = $row["userid"];
$self = $row;
}
}

//// Up/down stats ////////////////////////////////////////////////////////////



if (!isset($self))

{

$valid = @mysql_fetch_row(@mysql_query("SELECT COUNT(*) FROM peers WHERE torrent=$torrentid AND passkey=" . sqlesc($passkey)));

if ($valid[0] >= 1 && $seeder == 'no') err("Connection limit exceeded! You may only leech from one location at a time.");

if ($valid[0] >= 3 && $seeder == 'yes') err("Connection limit exceeded!");


if ($left > 0 && $user['class'] < UC_VIP && $TBDEV['user_ratios'])
{
$gigs = $user["uploaded"] / (1024*1024*1024);
$elapsed = floor((TIME_NOW - $torrent["ts"]) / 3600);
$ratio = (($user["downloaded"] > 0) ? ($user["uploaded"] / $user["downloaded"]) : 1);
if ($ratio < 0.5 || $gigs < 5) $wait = 48;
elseif ($ratio < 0.65 || $gigs < 6.5) $wait = 24;
elseif ($ratio < 0.8 || $gigs < 8) $wait = 12;
elseif ($ratio < 0.95 || $gigs < 9.5) $wait = 6;
else $wait = 0;
if ($elapsed < $wait)
err("Not authorized (" . ($wait - $elapsed) . "h) - READ THE FAQ!");
}
}
else
{
$upthis = max(0, $uploaded - $self["uploaded"]);
$downthis = max(0, $downloaded - $self["downloaded"]);

if ($upthis > 0 || $downthis > 0)
mysql_query("UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=".$user['id']) or err("Tracker error 3");
}

///////////////////////////////////////////////////////////////////////////////


$updateset = array();

if ($event == "stopped")
{
if (isset($self))
{
mysql_query("DELETE FROM peers WHERE $selfwhere");
if (mysql_affected_rows())
{
if ($self["seeder"] == "yes")
$updateset[] = "seeders = seeders - 1";
else
$updateset[] = "leechers = leechers - 1";
}
}
}
else
{
if ($event == "completed")
$updateset[] = "times_completed = times_completed + 1";

if (isset($self))
{
$compact = '';
// only update compact if ip or port has changed
   if( $self['ip'] != $ip || ($self['port']+0) != $port )
   {
     $compact = "compact = ".sqlesc(pack('Nn', ip2long($ip), $port)).',';
   }

mysql_query("UPDATE peers SET uploaded = $uploaded, downloaded = $downloaded,
to_go = $left, last_action = ".TIME_NOW.", $compact
seeder = '$seeder'"
. ($seeder == "yes" && $self["seeder"] != $seeder ? ",
finishedat = " . TIME_NOW : "") . " WHERE $selfwhere");

if (mysql_affected_rows() && $self["seeder"] != $seeder)
{
if ($seeder == "yes")
{
$updateset[] = "seeders = seeders + 1";
$updateset[] = "leechers = leechers - 1";
}
else
{
$updateset[] = "seeders = seeders - 1";
$updateset[] = "leechers = leechers + 1";
}
}
}
else
{
if ($event != "started")
err("Peer not found. ".$passkey." Restart the torrent.");

if (portblacklisted($port))
{
err("Port $port is blacklisted.");
}
elseif ( $TBDEV['connectable_check'] )
{
$sockres = @fsockopen($ip, $port, $errno, $errstr, 5);
if (!$sockres)
$connectable = "no";
else
{
$connectable = "yes";
@fclose($sockres);
}
}
else
{
     $connectable = 'yes';
}
   
   $compact = sqlesc(pack('Nn', ip2long($ip), $port));
   
$ret = mysql_query("INSERT INTO peers (connectable, torrent, peer_id, compact, ip, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, agent, passkey) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", $compact, " . sqlesc($ip) . ", $port, $uploaded, $downloaded, $left, ".TIME_NOW.", ".TIME_NOW.", '$seeder', {$user['id']}, " . sqlesc($agent) . "," . sqlesc($passkey) . ")");

if ($ret)
{
if ($seeder == "yes")
$updateset[] = "seeders = seeders + 1";
else
$updateset[] = "leechers = leechers + 1";
}
}
}

if ($seeder == "yes")
{
if ($torrent["banned"] != "yes")
$updateset[] = "visible = 'yes'";

$updateset[] = "last_action = ".TIME_NOW;
}

if (count($updateset))
mysql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = $torrentid");

benc_resp_raw($resp);



?>




www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
2022-10-10 20:12:58
to me the TT client response is not correct - but why does it work lol
here is TT code
//DO SOME BENC STUFF TO THE PEERS CONNECTION
$resp = "d8:completei$torrent[seeders]e10:downloadedi$torrent[times_completed]e10:incompletei$torrent[leechers]e";
$resp .= benc_str("interval") . "i" . $site_config['announce_interval'] . "e" . benc_str("min interval") . "i300e" . benc_str("peers");
unset($self);
while ($row = mysqli_fetch_assoc($res)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}

$peers .= "d" . benc_str("ip") . benc_str($row["ip"]);
       if (!$no_peer_id)
$peers .= benc_str("peer id") . benc_str($row["peer_id"]);
       $peers .= benc_str("port") . "i" . $row["port"] . "ee";
}
$resp .= "l{$peers}e";
$resp .= "ee";


but its mixed up and missing : in a few places here is a good string
d8:intervali60e12:min intervali30e8:completei2e10:incompletei0e5:peersld2:ip13:83.149.106.184:porti19874eed2:ip12:86.28.208.924:porti41402eeee

i have left no_peer_id off for now but this works for me
//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = mysqli_fetch_assoc($res)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}

$peers .= "d2:ip".strlen($row['ip']).":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";


here is full announce for v2 with debug make file call test.txt and place in same place as announce lets see what we are sending to client

you can always name this announce1.php & change one in seedbox to save connecting all torrents in seedbox

<?php
// Please Note: Languages should not be implemented here...
             
error_reporting(0);
// Set Database Settings
define("DB_HOST", "localhost");
define("DB_USER", "torrent1");
define("DB_PASS", "password");
define("DB_NAME", "dbname");
define('DB_CHAR', 'utf8');

// Set Database Connection
$opt = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
   PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
   $pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
   //die(response('The Database Details Are Incorrect'));
}

// Register custom exception handler

//    include "../app/helpers/exception_helper.php";
//    set_exception_handler("handleUncaughtException");
function pdo($pdo, $sql, $args = NULL)
{
       if (!$args) {
           return $pdo->query($sql);
       }
       $stmt = $pdo->prepare($sql);
       $stmt->execute($args);
       return $stmt;
}

$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;
function sqlesc($x)
{
   if (!is_numeric($x)) {
       $x = "'" . $x . "'";
   }
   return $x;
}
function unesc($x) {
stripslashes($x);
return $x;
}

function err($msg) {
  return benc_resp_raw("d".benc_str("failure reason").benc_str($msg)."e");
}

function benc_str($s) {
return strlen($s) . ":$s";
}

function benc_int($i) {
return "i" . $i . "e";
}

function benc_resp_raw($x) {
header("Content-Type: text/plain");
header("Pragma: no-cache");

if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else
print($x);

exit();
}

function gmtime() {
return strtotime(get_date_time());
}

function get_date_time($timestamp = 0) {
if ($timestamp)
return date("Y-m-d H:i:s", $timestamp);
else
return gmdate("Y-m-d H:i:s");
}

function portblacklisted($port) {
// direct connect
if ($port >= 411 && $port <= 413) return true;

// kazaa
if ($port == 1214) return true;

// gnutella
if ($port >= 6346 && $port <= 6347) return true;

// emule
if ($port == 4662) return true;

// winmx
if ($port == 6699) return true;

return false;
}

//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////
                                             
// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];
if (
   preg_match('%^Mozilla/|^Opera/|^Links |^Lynx/%i', $agent) ||
   isset($_SERVER['HTTP_COOKIE']) ||
   isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ||
   isset($_SERVER['HTTP_ACCEPT_CHARSET'])
   )
   err("torrent not registered with this tracker CODE 1");

//GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey","info_hash","peer_id","ip","event") as $x) {
   if(isset($_GET["$x"])) {
   $GLOBALS[$x] = "" . $_GET[$x];
   }
}

foreach (array("port","downloaded","uploaded","left") as $x)
   $GLOBALS[$x] = 0 + $_GET[$x];

foreach (array("passkey","info_hash","peer_id","port","downloaded","uploaded","left") as $x)
if (!isset($x))
err("Missing key: $x");

$no_peer_id = (int) $_GET["no_peer_id"];


   //foreach (array("info_hash", "peer_id") as $x) {
   foreach (array("info_hash") as $x) {
   if (strlen($GLOBALS[$x]) != 20){
       err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
   }
}
   unset($x);


if ($MEMBERSONLY){
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}

$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
//$peer_id = bin2hex($peer_id); todo

foreach(array("num want", "numwant", "num_want") as $k)
{
   if (isset($_GET[$k]))
   {
       $rsize = (int) $_GET[$k];
       break;
   }
}

//PORT CHECK
if (!$port || $port > 0xffff)
   err("invalid port");

//TRACKER EVENT CHECK
if (!isset($event))
   $event = "";

$seeder = ($left == 0) ? "yes" : "no";

$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get
           
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get

$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get

$userid = 0;
if ($MEMBERSONLY){
//check passkey is valid, and get users details
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user)
err("Cannot locate a user with that passkey!");

$userid = $user["id"]; //etc
}


//check torrent is valid and get torrent fields
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=".sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();

if (!$torrent)
   err("Torrent not found on this tracker - hash = " . $info_hash);
if ($torrent["banned"]=='yes')
   err("Torrent has been banned - hash = " . $info_hash);
$torrentid = $torrent["id"];


//Now get data from peers table
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit){
   $limit = "ORDER BY RAND() LIMIT $peerlimit";
}else{
   $limit = "";
}
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid $limit") or err("Error Selecting Peers")->fetch(PDO::FETCH_ASSOC);

//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}

$peers .= "d2:ip".strlen($row['ip']).":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";

$selfwhere = "torrent = $torrentid AND peer_id = ".sqlesc($peer_id);



// FILL $SELF WITH DETAILS FROM PEERS TABLE (CONNECTING PEERS DETAILS)
if (!isset($self)){
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE $selfwhere");
$row = $res->fetch(PDO::FETCH_ASSOC);
if ($row){
       $self = $row;
}
}
// END $SELF FILL


if (!isset($self)){ //IF PEER IS NOT IN PEERS TABLE DO THE WAIT TIME CHECK

}else{
   $upthis = max(0, $uploaded - $self["uploaded"]);
   $downthis = max(0, $downloaded - $self["downloaded"]);

   if (($upthis > 0 || $downthis > 0)){ // LIVE STATS!)
if ($torrent["freeleech"] == 1){
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}else{
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}
   }
}//END WAIT AND STATS UPDATE

$updateset = array();

////////////////// NOW WE DO THE TRACKER EVENT UPDATES ///////////////////

if ($event == "stopped") { // UPDATE "STOPPED" EVENT
       $RUN = pdo($pdo, "DELETE FROM peers WHERE $selfwhere");
       if ($RUN){
           if ($self["seeder"] == "yes")
               $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
           else
                $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
       }
}

if ($event == "completed") { // UPDATE "COMPLETED" EVENT    
   $updateset[] = "times_completed = times_completed + 1";

if ( $MEMBERSONLY )
{
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '".get_date_time()."')");
//uncomment below if using snatched table
//SQL_Query_exec("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
}
}//END COMPLETED

if (isset($self)){// NO EVENT? THEN WE MUST BE A NEW PEER OR ARE NOW SEEDING A COMPLETED TORRENT
   
   pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '".get_date_time()."', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE $selfwhere");

   if ($self["seeder"] != $seeder){
       if ($seeder == "yes"){
           $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
            $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
       } else {
           $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
           $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
       }
   }

} else {

   $ret = pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '".get_date_time()."', '".get_date_time()."', '$seeder', '$userid', " . sqlesc($agent) . ")");
   
   if ($ret){
       if ($seeder == "yes")
           $updateset[] = "seeders = seeders + 1";
       else
           $updateset[] = "leechers = leechers + 1";
   }
}

//////////////////    END TRACKER EVENT UPDATES ///////////////////

// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
   if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
       $updateset[] = "visible = 'yes'";
   $updateset[] = "last_action = '".get_date_time()."'";
}

// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset))
   pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");

function mydebug($msg) {
if(is_writeable('test.txt')) {
$fh = fopen('test.txt','a+');
fputs($fh,"[Log] ".date("d.m.Y H:i:s")." $msg\n");
fclose($fh);
}
}

mydebug($resp);
// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp);


Last edited by M-jay warn on 2022-10-10 20:36:06
2022-10-10 21:19:33
The problem is here
isset($_SERVER['HTTP_COOKIE'])

Tracker sending invalid data: <NULL>
2022-10-10 21:55:47
Hi Coco,
I don't have this part of the code anywhere at all (I use PHP7)

M-Jay
No changes, still red all
All statistic (lechers, seeders, completed) working well but users can't download
Other users have same problem too

Regards guys


www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
Last edited by Botanicar on 2022-10-11 07:36:29
2022-10-11 11:53:07
OK guys, good news for me and other guys having similar problems.....
Some of the torrents are GREEN today (chmod announce.php to the correct values) and 95% of the red ones turned them GREEN

Hope M-Jay finds the right solution now to avoid sql data in the file (announce.php)

Here is the one that works now, but statistic about seeders / leechers and completed is wrong as a hell  ðŸ˜²


<?php
// Please Note: Languages should not be implemented here...
           
error_reporting(0);
// Set Database Settings
define("DB_HOST", "localhost");
define("DB_USER", "db_username");
define("DB_PASS", "db_password");
define("DB_NAME", "db_name");
define('DB_CHAR', 'utf8');

// Set Database Connection
$opt = array(
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
  $pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
  //die(response('The Database Details Are Incorrect'));
}

// Register custom exception handler

//    include "../app/helpers/exception_helper.php";
//    set_exception_handler("handleUncaughtException");
function pdo($pdo, $sql, $args = NULL)
{
      if (!$args) {
          return $pdo->query($sql);
      }
      $stmt = $pdo->prepare($sql);
      $stmt->execute($args);
      return $stmt;
}

$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;
function sqlesc($x)
{
  if (!is_numeric($x)) {
      $x = "'" . $x . "'";
  }
  return $x;
}
function unesc($x) {
stripslashes($x);
return $x;
}

function err($msg) {
 return benc_resp_raw("d".benc_str("failure reason").benc_str($msg)."e");
}

function benc_str($s) {
return strlen($s) . ":$s";
}

function benc_int($i) {
return "i" . $i . "e";
}

function benc_resp_raw($x) {
header("Content-Type: text/plain");
header("Pragma: no-cache");

if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else
print($x);

exit();
}

function gmtime() {
return strtotime(get_date_time());
}

function get_date_time($timestamp = 0) {
if ($timestamp)
return date("Y-m-d H:i:s", $timestamp);
else
return gmdate("Y-m-d H:i:s");
}

function portblacklisted($port) {
// direct connect
if ($port >= 411 && $port <= 413) return true;

// kazaa
if ($port == 1214) return true;

// gnutella
if ($port >= 6346 && $port <= 6347) return true;

// emule
if ($port == 4662) return true;

// winmx
if ($port == 6699) return true;

return false;
}

//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////
                                           
// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];
if (
  preg_match('%^Mozilla/|^Opera/|^Links |^Lynx/%i', $agent) ||
  isset($_SERVER['HTTP_COOKIE']) ||
  isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ||
  isset($_SERVER['HTTP_ACCEPT_CHARSET'])
  )
  err("torrent not registered with this tracker CODE 1");

//GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey","info_hash","peer_id","ip","event") as $x) {
  if(isset($_GET["$x"])) {
  $GLOBALS[$x] = "" . $_GET[$x];
  }
}

foreach (array("port","downloaded","uploaded","left") as $x)
  $GLOBALS[$x] = 0 + $_GET[$x];

foreach (array("passkey","info_hash","peer_id","port","downloaded","uploaded","left") as $x)
if (!isset($x))
err("Missing key: $x");

$no_peer_id = (int) $_GET["no_peer_id"];


  //foreach (array("info_hash", "peer_id") as $x) {
  foreach (array("info_hash") as $x) {
  if (strlen($GLOBALS[$x]) != 20){
      err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
  }
}
  unset($x);


if ($MEMBERSONLY){
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}

$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
//$peer_id = bin2hex($peer_id); todo

foreach(array("num want", "numwant", "num_want") as $k)
{
  if (isset($_GET[$k]))
  {
      $rsize = (int) $_GET[$k];
      break;
  }
}

//PORT CHECK
if (!$port || $port > 0xffff)
  err("invalid port");

//TRACKER EVENT CHECK
if (!isset($event))
  $event = "";

$seeder = ($left == 0) ? "yes" : "no";

$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get
         
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get

$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get

$userid = 0;
if ($MEMBERSONLY){
//check passkey is valid, and get users details
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user)
err("Cannot locate a user with that passkey!");

$userid = $user["id"]; //etc
}


//check torrent is valid and get torrent fields
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=".sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();

if (!$torrent)
  err("Torrent not found on this tracker - hash = " . $info_hash);
if ($torrent["banned"]=='yes')
  err("Torrent has been banned - hash = " . $info_hash);
$torrentid = $torrent["id"];


//Now get data from peers table
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit){
  $limit = "ORDER BY RAND() LIMIT $peerlimit";
}else{
  $limit = "";
}
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid $limit") or err("Error Selecting Peers")->fetch(PDO::FETCH_ASSOC);

//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}

$peers .= "d2:ip".strlen($row['ip']).":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";

$selfwhere = "torrent = $torrentid AND peer_id = ".sqlesc($peer_id);



// FILL $SELF WITH DETAILS FROM PEERS TABLE (CONNECTING PEERS DETAILS)
if (!isset($self)){
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE $selfwhere");
$row = $res->fetch(PDO::FETCH_ASSOC);
if ($row){
      $self = $row;
}
}
// END $SELF FILL


if (!isset($self)){ //IF PEER IS NOT IN PEERS TABLE DO THE WAIT TIME CHECK

}else{
  $upthis = max(0, $uploaded - $self["uploaded"]);
  $downthis = max(0, $downloaded - $self["downloaded"]);

  if (($upthis > 0 || $downthis > 0)){ // LIVE STATS!)
if ($torrent["freeleech"] == 1){
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}else{
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}
  }
}//END WAIT AND STATS UPDATE

$updateset = array();

////////////////// NOW WE DO THE TRACKER EVENT UPDATES ///////////////////

if ($event == "stopped") { // UPDATE "STOPPED" EVENT
      $RUN = pdo($pdo, "DELETE FROM peers WHERE $selfwhere");
      if ($RUN){
          if ($self["seeder"] == "yes")
              $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
          else
               $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
      }
}

if ($event == "completed") { // UPDATE "COMPLETED" EVENT    
  $updateset[] = "times_completed = times_completed + 1";

if ( $MEMBERSONLY )
{
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '".get_date_time()."')");
//uncomment below if using snatched table
//SQL_Query_exec("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
}
}//END COMPLETED

if (isset($self)){// NO EVENT? THEN WE MUST BE A NEW PEER OR ARE NOW SEEDING A COMPLETED TORRENT
 
  pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '".get_date_time()."', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE $selfwhere");

  if ($self["seeder"] != $seeder){
      if ($seeder == "yes"){
          $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
           $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
      } else {
          $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
          $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
      }
  }

} else {

  $ret = pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '".get_date_time()."', '".get_date_time()."', '$seeder', '$userid', " . sqlesc($agent) . ")");
 
  if ($ret){
      if ($seeder == "yes")
          $updateset[] = "seeders = seeders + 1";
      else
          $updateset[] = "leechers = leechers + 1";
  }
}

//////////////////    END TRACKER EVENT UPDATES ///////////////////

// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
  if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
      $updateset[] = "visible = 'yes'";
  $updateset[] = "last_action = '".get_date_time()."'";
}

// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset))
  pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");

function mydebug($msg) {
if(is_writeable('test.txt')) {
$fh = fopen('test.txt','a+');
fputs($fh,"[Log] ".date("d.m.Y H:i:s")." $msg\n");
fclose($fh);
}
}

mydebug($resp);
// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp);



www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
Last edited by Botanicar on 2022-10-11 12:13:39
2022-10-11 12:17:55
I got this error message when I try to access directly to my first announce.php

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; TTCache has a deprecated constructor in /home/exyusub/public_html/backend/cache.php on line 10
Eat my cunt. Why are you doing this? None of this works this way


And this message on the new one:

d14:failure reason47:torrent not registered with this tracker CODE 1e



www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
2022-10-11 14:11:26
try replace announce1 with this, i removed the code preventing direct access for now which caused the error - we can add back once it works thjis is what direct access looks like https://torrenttrader.uk/announce1.php
i also moved sql details back to file
<?php
// stat here

error_reporting(0);

require_once("backend/mysql.php");

// Set Database Settings
define("DB_HOST", $mysql_host);
define("DB_USER", $mysql_user);
define("DB_PASS", $mysql_pass);
define("DB_NAME", $mysql_db);
define('DB_CHAR', 'utf8');

// Set Database Connection
$opt = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
   PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
   $pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
   err('The Database Details Are Incorrect');
}

// Register custom exception handler

//    include "../app/helpers/exception_helper.php";
//    set_exception_handler("handleUncaughtException");
function pdo($pdo, $sql, $args = NULL)
{
   try {
       if (!$args) {
           return $pdo->query($sql);
       }
       $stmt = $pdo->prepare($sql);
       $stmt->execute($args);
       return $stmt;
   } catch (\Exception $e) {
       err($e);
   }
}

$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;
function sqlesc($x)
{
   if (!is_numeric($x)) {
       $x = "'" . $x . "'";
   }
   return $x;
}
function unesc($x)
{
   stripslashes($x);
   return $x;
}

function err($msg)
{
   return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}

function benc_str($s)
{
   return strlen($s) . ":$s";
}

function benc_int($i)
{
   return "i" . $i . "e";
}

function benc_resp_raw($x)
{
   header("Content-Type: text/plain");
   header("Pragma: no-cache");

   if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
       header("Content-Encoding: gzip");
       echo gzencode($x, 9, FORCE_GZIP);
   } else
       print($x);

   exit();
}

function gmtime()
{
   return strtotime(get_date_time());
}

function get_date_time($timestamp = 0)
{
   if ($timestamp)
       return date("Y-m-d H:i:s", $timestamp);
   else
       return gmdate("Y-m-d H:i:s");
}

function portblacklisted($port)
{
   // direct connect
   if ($port >= 411 && $port <= 413) return true;

   // kazaa
   if ($port == 1214) return true;

   // gnutella
   if ($port >= 6346 && $port <= 6347) return true;

   // emule
   if ($port == 4662) return true;

   // winmx
   if ($port == 6699) return true;

   return false;
}

//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////

// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];

//GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
   if (isset($_GET["$x"])) {
       $GLOBALS[$x] = "" . $_GET[$x];
   }
}

foreach (array("port", "downloaded", "uploaded", "left") as $x) {
   $GLOBALS[$x] = 0 + $_GET[$x];
}

foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
   if (!isset($x)) {
       err("Missing key: $x");
   }
}

$no_peer_id = (int) $_GET["no_peer_id"];


//foreach (array("info_hash", "peer_id") as $x) {
foreach (array("info_hash") as $x) {
   if (strlen($GLOBALS[$x]) != 20) {
       err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
   }
}
unset($x);


if ($MEMBERSONLY) {
   if (strlen($passkey) != 32)
       err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}

$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
//$peer_id = bin2hex($peer_id); todo

foreach (array("num want", "numwant", "num_want") as $k) {
   if (isset($_GET[$k])) {
       $rsize = (int) $_GET[$k];
       break;
   }
}

//PORT CHECK
if (!$port || $port > 0xffff) {
   err("invalid port");
}

//TRACKER EVENT CHECK
if (!isset($event)) {
   $event = "";
}
$seeder = ($left == 0) ? "yes" : "no";

$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get

$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get

$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get

$userid = 0;
if ($MEMBERSONLY) {
   //check passkey is valid, and get users details
   $res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
   $user = $res->fetch();
   if (!$user) {
       err("Cannot locate a user with that passkey!");
   }
   $userid = $user["id"]; //etc
}


//check torrent is valid and get torrent fields
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=" . sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();

if (!$torrent) {
   err("Torrent not found on this tracker - hash = " . $info_hash);
} elseif ($torrent["banned"] == 'yes') {
   err("Torrent has been banned - hash = " . $info_hash);
}
$torrentid = $torrent["id"];


//Now get data from peers table
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
   $limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
   $limit = "";
}
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid $limit") or err("Error Selecting Peers");

//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
   if ($row["peer_id"] === $peer_id) {
       $self = $row;
       continue;
   }

   $peers .= "d2:ip" . strlen($row['ip']) . ":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";

$selfwhere = "torrent = $torrentid AND peer_id = " . sqlesc($peer_id);



// FILL $SELF WITH DETAILS FROM PEERS TABLE (CONNECTING PEERS DETAILS)
if (!isset($self)) {
   $res = pdo($pdo, "SELECT $peerfields FROM peers WHERE $selfwhere");
   $row = $res->fetch(PDO::FETCH_ASSOC);
   if ($row) {
       $self = $row;
   }
}
// END $SELF FILL


if (!isset($self)) { //IF PEER IS NOT IN PEERS TABLE DO THE WAIT TIME CHECK

} else {
   $upthis = max(0, $uploaded - $self["uploaded"]);
   $downthis = max(0, $downloaded - $self["downloaded"]);

   if (($upthis > 0 || $downthis > 0)) { // LIVE STATS!)
       if ($torrent["freeleech"] == 1) {
           pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
       } else {
           pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
       }
   }
} //END WAIT AND STATS UPDATE

$updateset = array();

////////////////// NOW WE DO THE TRACKER EVENT UPDATES ///////////////////

if ($event == "stopped") { // UPDATE "STOPPED" EVENT
   $RUN = pdo($pdo, "DELETE FROM peers WHERE $selfwhere");
   if ($RUN) {
       if ($self["seeder"] == "yes")
           $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
       else
           $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
   }
}

if ($event == "completed") { // UPDATE "COMPLETED" EVENT    
   $updateset[] = "times_completed = times_completed + 1";

   if ($MEMBERSONLY) {
       pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
       //uncomment below if using snatched table
       //SQL_Query_exec("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
   }
} //END COMPLETED

if (isset($self)) { // NO EVENT? THEN WE MUST BE A NEW PEER OR ARE NOW SEEDING A COMPLETED TORRENT

   pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '" . get_date_time() . "', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE $selfwhere");

   if ($self["seeder"] != $seeder) {
       if ($seeder == "yes") {
           $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
           $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
       } else {
           $updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
           $updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
       }
   }
} else {

   $ret = pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '" . get_date_time() . "', '" . get_date_time() . "', '$seeder', '$userid', " . sqlesc($agent) . ")");

   if ($ret) {
       if ($seeder == "yes")
           $updateset[] = "seeders = seeders + 1";
       else
           $updateset[] = "leechers = leechers + 1";
   }
}

//////////////////    END TRACKER EVENT UPDATES ///////////////////

// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
   if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
       $updateset[] = "visible = 'yes'";
   $updateset[] = "last_action = '" . get_date_time() . "'";
}

// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset)) {
   pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}

function mydebug($msg)
{
   if (is_writeable('test.txt')) {
       $fh = fopen('test.txt', 'a+');
       fputs($fh, "[Log] " . date("d.m.Y H:i:s") . " $msg\n");
       fclose($fh);
   }
}

mydebug($resp);
// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp);
Last edited by M-jay warn on 2022-10-11 16:08:09
2022-10-11 19:26:41
M-Jay
working like charm, but still same problem with number of seeders/leechers and completed in torrent info data

I upload one of new torrents with new announce and after 10 minutes shows 4 seeders, but torrent is GREEN that was point hahahaha



www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
Last edited by Botanicar on 2022-10-11 19:27:29
2022-10-11 20:19:55
fantastic now it works i have been preparing this - much cleaner then the 2.08 announce and will fix counting seeders and leechers

these lines need checking
1) allow members only
// Member Settings
$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;

2) maybe place // in front so you dont log everything
mydebug($resp);


<?php
// Hide Errors
error_reporting(0);

// Get Settings
require_once("backend/mysql.php");

// Set Database Settings
define("DB_HOST", $mysql_host);
define("DB_USER", $mysql_user);
define("DB_PASS", $mysql_pass);
define("DB_NAME", $mysql_db);
define('DB_CHAR', 'utf8');

// Set Database Connection
$opt = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
   PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
   $pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
   err('The Database Details Are Incorrect');
}

// SQL Function To Display Errors
function pdo($pdo, $sql, $args = NULL)
{
   try {
       if (!$args) {
           return $pdo->query($sql);
       }
       $stmt = $pdo->prepare($sql);
       $stmt->execute($args);
       return $stmt;
   } catch (\Exception $e) {
       err($e);
   }
}

// Write Response To File
function mydebug($msg)
{
   if (is_writeable('test.txt')) {
       $fh = fopen('test.txt', 'a+');
       fputs($fh, "[Log] " . date("d.m.Y H:i:s") . " $msg\n");
       fclose($fh);
   }
}

// Member Settings
$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;

// Default Functions
function sqlesc($x)
{
   if (!is_numeric($x)) {
       $x = "'" . $x . "'";
   }
   return $x;
}
function unesc($x)
{
   stripslashes($x);
   return $x;
}
function err($msg)
{
   return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}
function benc_str($s)
{
   return strlen($s) . ":$s";
}
function benc_int($i)
{
   return "i" . $i . "e";
}
function benc_resp_raw($x)
{
   header("Content-Type: text/plain");
   header("Pragma: no-cache");
   if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
       header("Content-Encoding: gzip");
       echo gzencode($x, 9, FORCE_GZIP);
   } else {
       print($x);
   }
   exit();
}
function gmtime()
{
   return strtotime(get_date_time());
}
function get_date_time($timestamp = 0)
{
   if ($timestamp) {
       return date("Y-m-d H:i:s", $timestamp);
   } else {
       return gmdate("Y-m-d H:i:s");
   }
}
function portblacklisted($port)
{
   if ($port >= 411 && $port <= 413) {
       // direct connect
       return true;
   } elseif ($port == 1214) {
       // kazaa
       return true;
   } elseif ($port >= 6346 && $port <= 6347) {
       // gnutella
       return true;
   } elseif ($port == 4662) {
       // emule
       return true;
   } elseif ($port == 6699) {
       // winmx
       return true;
   }
   return false;
}

// NOW WE DO THE ANNOUNCE CODE

// Agent
$agent = $_SERVER["HTTP_USER_AGENT"];

// Get Client Details
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
   if (isset($_GET["$x"])) {
       $GLOBALS[$x] = "" . $_GET[$x];
   }
}

foreach (array("port", "downloaded", "uploaded", "left") as $x) {
   $GLOBALS[$x] = 0 + $_GET[$x];
}

foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
   if (!isset($x)) {
       err("Missing key: $x");
   }
}

$no_peer_id = (int) $_GET["no_peer_id"];

foreach (array("info_hash") as $x) {
   if (strlen($GLOBALS[$x]) != 20) {
       err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
   }
}
unset($x);

if ($MEMBERSONLY) {
   if (strlen($passkey) != 32)
       err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}

$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);

foreach (array("num want", "numwant", "num_want") as $k) {
   if (isset($_GET[$k])) {
       $rsize = (int) $_GET[$k];
       break;
   }
}

if (!$port || $port > 0xffff) {
   err("invalid port");
}

if (!isset($event)) {
   $event = "";
}

$seeder = ($left == 0) ? "yes" : "no";

// Wanted Data From DB
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get
$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get

// Check User
$userid = 0;
if ($MEMBERSONLY) {
   $res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
   $user = $res->fetch();
   if (!$user) {
       err("Cannot locate a user with that passkey!");
   }
   $userid = $user["id"]; //etc
}

// Check Torrent
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=" . sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();
if (!$torrent) {
   err("Torrent not found on this tracker - hash = " . $info_hash);
} elseif ($torrent["banned"] == 'yes') {
   err("Torrent has been banned - hash = " . $info_hash);
}
$torrentid = $torrent["id"];

// Limit Number Of Peers
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
   $limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
   $limit = "";
}

// Check Peer New Or Old
$sql = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid  AND peer_id = " . sqlesc($peer_id) . "") or err("Error Selecting Peers");
$res = $sql->fetch(PDO::FETCH_ASSOC);
if ($res) {
   // Already Peer So Update User & Peer Table
   $upthis = max(0, $uploaded - $res["uploaded"]);
   $downthis = max(0, $downloaded - $res["downloaded"]);
   if (($upthis > 0 || $downthis > 0)) {
       if ($torrent["freeleech"] == 1) {
           pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
       } else {
           pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
       }
   }
   pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '" . get_date_time() . "', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
} else {
   // New Peer So Add
   pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '" . get_date_time() . "', '" . get_date_time() . "', '$seeder', '$userid', " . sqlesc($agent) . ")");
}

// Now Do Events
if ($event == "stopped") {
   pdo($pdo, "DELETE FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
}
if ($event == "completed") {
   $updateset[] = "times_completed = times_completed + 1";
   if ($MEMBERSONLY) {
       pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
   }
}

// Now We Did Current Peer Lets Get All Peers
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid");
// Sort Response
$seeders = 0;
$leechers = 0;
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
   if ($row['seeder'] == 'no') {
       $leechers++;
   } else {
       $seeders++;
   }
   $peers .= "d2:ip" . strlen($row['ip']) . ":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$peerlist['seeders'] = $seeders;
$peerlist['leechers'] = $leechers;
$resp = "d8:intervali600e12:min intervali300e8:completei$peerlist[seeders]e10:incompletei$peerlist[leechers]e5:peersl$peerlist[list]ee";

// Now Update Torrent
$updateset = array();
$updateset[] = "seeders = $peerlist[seeders]";
$updateset[] = "leechers = $peerlist[leechers]";
if ($seeder == "yes") {
   if ($torrent["banned"] != "yes")
       $updateset[] = "visible = 'yes'";
   $updateset[] = "last_action = '" . get_date_time() . "'";
}
if (count($updateset)) {
   pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}

// Send Bencoded Data To File For Debug
mydebug($resp);

// Finally Send Data To Client
benc_resp_raw($resp);
Last edited by M-jay warn on 2022-10-11 20:36:14
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 1
  • Members: 0
  • Guests online: 1
  • Comments: 3
  • Messages: 1,728