I've taken my own announce I've developed over some time and converted to MySQLi for those of you who wish to test this. Just point the tracker to this script.
I hope to replace the old one with something much faster and full-featured (those BEPs).
This is a conversion from a fully and very busy PDO version of this, with a class in place.
First, add the columns
This is the full announce script. Download files in LAST post below.
I hope to replace the old one with something much faster and full-featured (those BEPs).
This is a conversion from a fully and very busy PDO version of this, with a class in place.
First, add the columns
CREATE TABLE happyhour (id int(10) NOT NULL AUTO_INCREMENT, userid int(10) NOT NULL DEFAULT 0, torrentid int(10) NOT NULL DEFAULT 0, multiplier float NOT NULL DEFAULT 0, PRIMARY KEY (id), KEY userid (userid, torrentid))
ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE peers ADD http_client TEXT;
ALTER TABLE peers ADD clientkey VARCHAR(10);
ALTER TABLE peers ADD completed TINYINT(1) NOT NULL DEFAULT 0;
ALTER TABLE peers ADD chosen_peer_id CHAR(40) DEFAULT '';
ALTER TABLE users ADD slots INT(10) DEFAULT 3;
This is the full announce script. Download files in LAST post below.
<?
//
// TorrentTrader - v2.x/v3.x
// $LastChangedDate: 2021-04-10 09:16:00 +0100 (Sat, 10 Apr 2021) $
// $LastChangedBy: storrents2020 $
//
// https://www.torrenttrader.uk
//
//
// v1.01
// - Resolved incorrect columns reflecting ST mainline.
// - Added inline MEMBERSONLY check (passkey/IP)
error_reporting(0);
require_once 'backend/mysql.php';
require_once 'backend/config.php';
require_once 'backend/classes/class.bencoding.php';
require_once 'backend/classes/class.mysqli.php';
$db = new DatabaseClass($mysql_host, $mysql_db, $mysql_user, $mysql_pass);
$timeout = 5; // fsockopen timeout (seconds)
$db->Remove('DELETE FROM peers WHERE last_action + INTERVAL 1 hour < CURRENT_TIMESTAMP');
header('Content-Type: text/plain');
function fail($reason)
{
die(bencode(array('failure reason' => $reason)));
}
function getip()
{
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
return $ip;
foreach (array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'HTTP_CF_CONNECTING_IP',
'REMOTE_ADDR'
) as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
return $ip;
}
}
}
}
} else {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
}
function ip2bytes($ip)
{
$res = '';
$parts = explode('.', $ip);
if (count($parts) !== 4) return null;
for ($i = 0; $i < 4; $i++) {
$b = $parts[$i];
if (!is_numeric($b)) return null;
$b = intval($b);
if ($b < 0 || $b >= 256) return null;
$res .= chr($b);
}
return $res;
}
// Happy Hour Upload Multiplier
function happyhour_multiplier(int $torrent_id, int $user_id)
{
global $db;
if ($site_config['MEMBERSONLY']) {
$res_happy = $db->Select('SELECT id, userid, torrentid, multiplier FROM happyhour WHERE userid = ?', [
'i', $user_id
]);
$happy = array();
if ($res_happy) {
if ($rowhappy = $res_happy) {
$happy[$rowhappy['torrentid']] = $rowhappy['multiplier'];
}
}
$db->Insert('INSERT INTO happyhour (userid, torrentid, multiplier) VALUES(?, ?, ?)', [
'iid', $user_id, $torrent_id, $happy
]);
if (!empty($happy) && isset($happy[$torrent_id])) return $happy[$torrent_id];
}
return false;
}
$keys = array(
'downloaded' => true,
'uploaded' => true,
'passkey' => false,
'username' => false,
'torrent_id' => false,
'token' => false,
'info_hash' => true,
'peer_id' => true,
'port' => true,
'no_peer_id' => false,
'ip' => false,
'numwant' => false,
'event' => false,
'left' => true,
'compact' => false,
'key' => 1,
);
$data = array();
foreach ($keys as $key => $req) {
if (array_key_exists($key, $_GET)) {
$data[$key] = $_GET[$key];
} else if ($req) {
fail(sprintf('Missing key: %s', $key));
}
}
$seeder = ($data['left'] == 0) ? 'yes' : 'no';
$client = substr($data['peer_id'], 0, 8);
$data['info_hash'] = bin2hex($data['info_hash']);
$data['peer_id'] = bin2hex($data['peer_id']);
// Peer authentication
$res = $db->Select('SELECT slots, id, passkey, username, class, enabled, uploaded, downloaded FROM users WHERE passkey = ? OR ip = ?', [
'ss', ($site_config['MEMBERSONLY'] ? $data['passkey'] : ''), ($site_config['MEMBERSONLY'] ? '' : $data['ip'])
]);
foreach ($res as $user_row)
// Check enabled user
if ($user_row['enabled'] == 'no') {
fail('Account not enabled.');
}
// Verify passkey
if (!hash_equals($user_row['passkey'], $data['passkey'])) {
fail('Passkey is invalid');
}
// Max Slots
if ($site_config['MEMBERSONLY'] && $seeder != 'yes') {
$maxslots = $db1->Select("SELECT COUNT(DISTINCT torrent) AS total, last_action FROM peers WHERE userid = ? AND seeder = 'no'", [
'i', $user_row['id']
]);
foreach($maxslots as $current) {
if ($current['total'] > $user_row['slots']) {
fail("$current[total]/$user_row[slots] download slots exceeded! Finish current transfers to reclaim slots.");
}
}
}
if (!is_numeric($data['port'])) fail('invalid port');
$data['port'] = intval($data['port']);
if ($data['port'] < 1 || $data['port'] >= 65536) fail('Invalid port');
if (array_key_exists('left', $data)) {
if (!is_numeric($data['left'])) fail('Invalid left');
$data['left'] = intval($data['left']);
if ($data['left'] < 0) fail('Invalid left');
}
if (!array_key_exists('ip', $data)) {
$data['ip'] = getip();
$try_keys = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP');
foreach ($try_keys as $key => &$value) {
if (array_key_exists($key, $_SERVER)) {
$potential_ip = trim(explode(',', $_SERVER[$key])[0]);
if (strpos($potential_ip, '10.') === 0) continue;
if (strpos($potential_ip, '192.168.') === 0) continue;
// TODO: 172.16.0.0/12 is also private
$data['ip'] = $potential_ip;
break;
}
}
}
if (array_key_exists('numwant', $data)) {
if (!is_numeric($data['numwant'])) fail('Invalid numwant');
$data['numwant'] = intval($data['numwant']);
if ($data['numwant'] < 0) $data['numwant'] = 1000;
if ($data['numwant'] > 1000) $data['numwant'] = 1000;
} else {
$data['numwant'] = 30;
}
$res = $db->Select('SELECT size, seeders, leechers, id, freeleech, name FROM torrents WHERE info_hash = ?', [
's', $data['info_hash']
]);
foreach ($res as $torrent_row)
$res = $db->Select('SELECT clientkey, peer_id, completed, seeder, last_action FROM peers WHERE userid = ? AND torrent = ? AND chosen_peer_id = ?', [
'iis', $user_row['id'], $torrent_row['id'], $data['peer_id']
]);
if (!$res) {
// Insert new peer
$peer_id = $db->Insert('INSERT INTO peers (clientkey, started, passkey, connectable, userid, torrent, chosen_peer_id, ip, port, client) VALUES (?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?)', [
'sssiissis', $data['key'], $data['passkey'], (fsockopen($data['ip'], $data['port'], $errno, $errstr, $timeout) ? 'yes' : 'no'), $user_row['id'], $torrent_row['id'], $data['peer_id'], $data['ip'], $data['port'], $client
]);
$peer_row = $peer_id;
} else {
foreach ($res as $peer_row) {
// Update existing peer
$db->Update('UPDATE peers SET passkey = ?, clientkey = ?, connectable = ?, to_go = ?, uploaded = ?, downloaded = ?, seeder = ?, client = ?, ip = ?, port = ?, last_action = CURRENT_TIMESTAMP WHERE peer_id = ?', [
'ssiiisssiss', $user_row['passkey'], (fsockopen($data['ip'], $data['port']) ? 'yes' : 'no'), $data['left'], max(0, $data['uploaded'] - $peer_row['uploaded']), max(0, $data['downloaded'] - $peer_row['downloaded']), $seeder, $client, $data['ip'], $data['port'], $peer_row['peer_id'], $data['key']
]);
// Download Upgrades
switch ($torrent_row['freeleech']) {
case 1:
$downloaded = 0; // Freeleech - Only upload counts
break;
case 'silver':
$downloaded = round($downloaded / 2); // Half the download
break;
case 'upboost':
$uploaded = round($uploaded * 5); // - 5X the upload
break;
case 'dlboost':
$downloaded = round($downloaded * 5); // - 5X the download
break;
case 0: // Non-freeleech
break;
}
// Happyhour Upload Multiplier
$happy_multiplier = happyhour_multiplier($torrent_row['torrent'], $user_row['id']);
if ($happy_multiplier !== false) { // && torrent_row[seedbonus] == [type]
$uploaded = $uploaded * $happy_multiplier;
$downloaded = 0;
// Log Multiplier
$event = "Happy Hour Upload Multiplier: X" . $happy_multiplier;
$db->Update('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, ?, ?, NOW(), 0)', [
'ss', $user_row['username'], $event
]);
}
// Update peers upload / download
if ($peer_row['seeder'] == 'no') {
$db->Update('UPDATE users SET uploaded = uploaded + ?, downloaded = downloaded + ? WHERE id = ?', [
'iii', $uploaded, $downloaded, $user_row['id']
]);
} elseif ($peer_row['seeder'] == 'yes' && $data['left'] === 0) {
$db->Update('UPDATE users SET uploaded = uploaded + ? WHERE id = ?', [
'ii', $uploaded, $user_row['id']
]);
}
}
}
// Client key check & update
if ($data['key'] !== $peer_row['clientkey']) {
$db->Update('UPDATE peers SET clientkey = ? WHERE peer_id = ?', [
'ss', $data['key'], $peer_row['peer_id']
]);
}
if (array_key_exists('left', $data)) {
$db->Update('UPDATE peers SET completed = ?, seeder = ? WHERE peer_id = ?', [
'iss', $data['left'], $seeder, $peer_row['peer_id']
]);
}
if ($data['event'] === 'stopped') {
$db->Remove('DELETE FROM peers WHERE peer_id = ?', [
's', $peer_row['peer_id']
]);
}
if ($data['event'] === 'paused') {
// BEP-21: Announce event=paused to HTTP trackers when partial seeding
}
if ($data['event'] === 'completed') {
$db->Remove('DELETE FROM peers WHERE peer_id = ?', [
's', $peer_row['peer_id']
]);
$db->Update('UPDATE torrents SET times_completed = times_completed + ? WHERE torrent_id = ?', [
'si', ($data['left'] === 0 ? 1 : 0), $torrent_row['id']
]);
}
$res = $db->Select('SELECT COUNT(NULLIF(p.completed, false)) AS complete, COUNT(NULLIF(t.times_completed, false)) AS downloaded, COUNT(NULLIF(p.completed, true)) AS incomplete FROM peers p LEFT JOIN torrents t ON t.id = p.torrent WHERE p.torrent = ?', [
'i', $torrent_row['id']
]);
foreach ($res as $comp_res) {
// Scrape
$output = array(
'interval' => 30 * 60,
'min interval' => 10 * 60, // BEP 31: Failure Retry Extension
'retry in' => 10 * 60, // BEP 31: Failure Retry Extension
'complete' => intval($comp_res['complete']),
'incomplete' => intval($comp_res['incomplete']),
'downloaded' => intval($comp_res['downloaded']),
'peers' => array(),
);
}
$res = $db->Select('SELECT chosen_peer_id, ip, port FROM peers WHERE torrent = ? AND peer_id != ? ORDER BY RAND() LIMIT ?', [
'isi', $torrent_row['id'], $peer_row['peer_id'], $data['numwant']
]);
foreach ($res as $row) {
$peer = array(
'ip' => $row['ip'],
'port' => intval($row['port']),
);
if (!array_key_exists('no_peer_id', $data)) {
$peer['peer_id'] = hex2bin($row['chosen_peer_id']);
}
$output['peers'] []= $peer;
}
if (array_key_exists('compact', $data)) {
$peer_data = '';
foreach ($output['peers'] as $peer) {
$bs = ip2bytes($peer['ip']);
if (is_null($bs)) continue;
$peer_data .= $bs;
$peer_data .= chr($peer['port'] >> 8);
$peer_data .= chr($peer['port'] & 0xff);
}
if (empty($output['peers']) || !empty($peer_data)) {
$output['peers'] = $peer_data;
}
}
// Log client/version
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$db->Update('UPDATE peers SET http_client = ? WHERE clientkey = ?', [
'ss', $_SERVER['HTTP_USER_AGENT'], $data['key']
]);
}
echo bencode($output);
Last edited by STorrents2020 on 2021-04-19 01:03:05
