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
add exception_helper.php to root
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
on 2022-10-06 19:48:56
on 2022-10-06 19:48:56

