The announce.php is over 20 years old and i have put off updating the torrent side of for ages but needed doing so here is some thing im playing with
[color=rgb(247, 218, 100)]UPDATED 19/09/20[/color]
Add Database.php to backend folder (pdo connection)
Replace announce.php ( i use snatched mod)
[color=rgb(247, 218, 100)]UPDATED 19/09/20[/color]
Add Database.php to backend folder (pdo connection)
Replace announce.php ( i use snatched mod)
<?php
require 'backend/config.php';
require 'backend/Database.php';
// Use the correct content-type
header("Content-type: Text/Plain");
header("Connection: Close");
// Add settings
define("__TTURL", $site_config['SITEURL']);
define("__MEMBERSONLY", $site_config["MEMBERSONLY"]);
define("__MEMBERSONLY_WAIT", $site_config["MEMBERSONLY_WAIT"]);
define('__INTERVAL', 1800); // Peer announce interval (Seconds)
define('__TIMEOUT', 60); // Time out if peer is this late to re-announce (Seconds)
define('__INTERVAL_MIN', 600); // Minimum announce interval (Seconds), Most clients honor this, but not all
define('__MAX_PPR', 25); // Never encode more than this number of peers in a single request
// Bencoding function, returns a bencoded dictionary (You may go ahead and enter custom keys in the dictionary)
function track($list, $c=0, $i=0, $completed=0) {
global $site_config;
if (is_string($list)) { // Did we get a string? Return an error to the client
return 'd14:failure reason'.strlen($list).':'.$list.'e';
}
$p = ''; // Peer directory
foreach($list as $d) { // Runs for each client
$pid = '';
if (!isset($no_peer_id)) { // Send out peer_ids in the reply
$real_id = $d[2];
$pid = '7:peer id'.strlen($real_id).':'.$real_id;
}
$p .= 'd2:ip'.strlen($d[0]).':'.$d[0].$pid.'4:porti'.$d[1].'ee';
}
// Add some other paramters in the dictionary and merge with peer list
$r = 'd8:completei'.$c.'e10:downloadedi'.$completed.'e10:incompletei'.$i.'e8:intervali'.$site_config['announce_interval'].'e12:min intervali'.$site_config['announce_interval'].'e5:peersl'.$p.'eee';
return $r;
}
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)) {
die("No Browser Access");
}
// GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $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)) {
die(track("Missing key: $x"));
}
}
if (strlen($peer_id) != 20) {
die(track("Invalid peer_id"));
}
$no_peer_id = (int) $_GET["no_peer_id"];
if (strlen($GLOBALS['info_hash']) == 20) {
$GLOBALS['info_hash'] = bin2hex($GLOBALS['info_hash']);
} else if (strlen($GLOBALS['info_hash']) != 40) {
die(track("Invalid info hash value."));
}
$GLOBALS['info_hash'] = strtolower($GLOBALS['info_hash']);
if (__MEMBERSONLY) {
if (strlen($passkey) != 32) {
die(track("Invalid passkey (" . strlen($passkey) . " - $passkey)"));
}
}
$ip = $_SERVER["REMOTE_ADDR"];
foreach (array("num want", "numwant", "num_want") as $k) {
if (isset($_GET[$k])) {
$rsize = (int) $_GET[$k];
break;
}
}
//PORT CHECK
if (!$port || $port > 0xffff) {
die(track("invalid port"));
}
//TRACKER EVENT CHECK
if (!isset($event)) {
$event = "";
}
$seeder = ($left == 0) ? "yes" : "no";
if (portblacklisted($port)) {
die(track("Port $port is blacklisted."));
}
$dbh = new Database();
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey, g.can_download"; //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 = $dbh->run("
SELECT $userfields
FROM users u
INNER JOIN groups g
ON u.class = g.group_id
WHERE u.passkey=? AND u.enabled = ? AND u.status = ? LIMIT 1", [$passkey, 'yes', 'confirmed'])
or die(track("Cannot Get User Details"));
$user = $res->fetch(PDO::FETCH_ASSOC);
if (!$user) {
die(track("Cannot locate a user with that passkey!"));
}
if ($user["can_download"] == "no") {
die(track("You do not have permission to download."));
}
$userid = $user["id"]; //etc
}
//check torrent is valid and get torrent fields
$res = $dbh->run("
SELECT $torrentfields
FROM torrents
WHERE info_hash=?
", [$info_hash]) or die(track("Cannot Get Torrent Details"));
$torrent = $res->fetch(PDO::FETCH_ASSOC);
if (!$torrent) {
die(track("Torrent not found on this tracker - hash = " . $info_hash));
}
if ($torrent["banned"] == 'yes') {
die(track("Torrent has been banned - hash = " . $info_hash));
}
$torrentid = $torrent["id"];
$numpeers = $torrent["numpeers"];
$updateset = array();
// Check if peer has been announced before
$res = $dbh->run("
SELECT $peerfields
FROM peers
WHERE torrent = $torrentid LIMIT 1")
or die(track("Error Selecting Peers"));
unset($current_peer);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row["peer_id"] === $peer_id) {
$current_peer = $row;
continue;
}
}
// So it's new lets do some checks
if (!isset($current_peer)) {
// Check connected
$sockres = @fsockopen($ip, $port, $errno, $errstr, 5);
if (!$sockres) {
$connectable = "no";
} else {
$connectable = "yes";
}
@fclose($sockres);
if (__MEMBERSONLY) {
// Check slots
$countslot = $dbh->run("
SELECT DISTINCT torrent
FROM peers WHERE userid =? AND seeder=?", [$userid, 'no']);
$slot = $countslot->rowCount();
$maxslot = $dbh->run("
SELECT `maxslots`
FROM `groups`
WHERE `group_id` = $user[class]")->fetchColumn();
if ($slot >= $maxslot) {
die(track("Maximum Slot exceeded! You may only download $maxslot torrent at a time."));
}
//check passkey isnt leaked
$sql = $dbh->run("
SELECT COUNT(*)
FROM peers
WHERE torrent=? AND passkey=?
", [$torrentid, $passkey]);
$valid = $sql->rowCount();
if ($valid >= 1 && $seeder == 'no') {
die(track("Connection limit exceeded! You may only leech from one location at a time."));
}
if ($valid >= 3 && $seeder == 'yes') {
die(track("Connection limit exceeded!"));
}
}
// Snatch
if ((__MEMBERSONLY) && (($seeder == 'no' && $torrent['freeleech'] == 0))) {
$dbh->run("INSERT INTO `snatched` (`uid`, `tid`, `stime`, `utime`) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE `utime` = ?", [$userid, $torrentid, gmtime(), gmtime(), gmtime()]);
}
// Insert announced peer
$ret = $dbh->run("
INSERT INTO peers
(connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client)
VALUES
(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
[$connectable, $torrentid, $peer_id, $ip, $passkey, $port, $uploaded, $downloaded, $left, get_date_time(), get_date_time(), $seeder, $userid, $agent]);
if ($ret) {
if ($seeder == "yes") {
$updateset[] = "seeders = seeders + 1";
} else {
$updateset[] = "leechers = leechers + 1";
}
}
} else { // it is a old peer
// snatch
$elapsed = ($current_peer['seeder'] == 'yes') ? $site_config['announce_interval'] - floor(($current_peer['ez'] - time()) / 60) : 0; //
$upthis = max(0, $uploaded - $current_peer["uploaded"]);
$downthis = max(0, $downloaded - $current_peer["downloaded"]);
if (($upthis > 0 || $downthis > 0 || $elapsed > 0) && $userid) { // LIVE STATS!)
if ($torrent["freeleech"] == 1) {
$dbh->run("UPDATE users SET uploaded = uploaded + $upthis
WHERE id=$userid") or die(track("Tracker error: Unable to update stats"));
} else {
$dbh->run("UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis
WHERE id=$userid") or die(track("Tracker error: Unable to update stats"));
// snatch
$dbh->run("UPDATE LOW_PRIORITY `snatched`
SET `uload` = `uload` + '$upthis', `dload` = `dload` + '$downthis', `utime` = '" . gmtime() . "', `ltime` = `ltime` + '$elapsed'
WHERE `tid` = '$torrentid'
AND `uid` = '$userid'");
}
}
$peerupd = $dbh->run("
UPDATE peers
SET ip = ?, passkey = ?, port = ?, uploaded = ?, downloaded = ?, to_go = ?, last_action = ?, client = ?, seeder = ? WHERE torrent = ? AND peer_id = ?",
[$ip, $passkey, $port, $uploaded, $downloaded, $left, get_date_time(), $agent, $seeder, $torrentid, $peer_id]
);
if ($peerupd && $current_peer["seeder"] != $seeder) {
if ($seeder == "yes") {
$updateset[] = "seeders = seeders + 1";
$updateset[] = "leechers = leechers - 1";
} else {
$updateset[] = "seeders = seeders - 1";
$updateset[] = "leechers = leechers + 1";
}
}
if ($event === 'stopped') {
// DELETE PEER AND REMOVE SEEDER OR LEECHER
if (isset($current_peer)) {
$q = $dbh->run(
'DELETE FROM peers WHERE torrent = ? AND passkey = ?',
[$torrentid, $passkey]
);
if ($q->rowCount()) {
if ($seeder == "yes") {
$updateset[] = "seeders = seeders - 1";
} else {
$updateset[] = "leechers = leechers - 1";
}
}
}
}
} //END
// UPDATE "COMPLETED" EVENT
if ($event == "completed") {
$updateset[] = "times_completed = times_completed + 1";
if (__MEMBERSONLY) {
$dbh->run("INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
}
// snatch
$dbh->run("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
} //END COMPLETED
// 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)) {
$dbh->run("UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or die(track("Tracker error: Unable to update torrent"));
}
//Now get data from peers table
$peerlimit = 50;
// $numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
$limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
$limit = "";
}
// Select ip, port, peer_id to send back to client
$res = $dbh->run("
SELECT ip, port, peer_id
FROM peers
WHERE torrent = $torrentid $limit") ;
$reply = array(); //To be encoded and sent to the client
while ($r=$res->fetch(PDO::FETCH_ASSOC)) { //Runs for every client with the same infohash
$reply[] = array($r['ip'], $r['port'], $r['peer_id']);
}
try {
$select_peers = $dbh->run("
SELECT seeders, leechers, times_completed
FROM torrents
WHERE info_hash=? LIMIT 1
", [$info_hash]);
$seeders = 0;
$leechers = 0;
$completed = 0;
if ($r = $select_peers->fetch(PDO::FETCH_ASSOC))
{
$seeders = $r['seeders'];
$leechers = $r['leechers'];
$completed = $r['times_completed'];
}
} catch (PDOException $e) {
die(track('Unable to select:'.$e->getMessage()));
}
// Final output to client
die(track($reply, $seeders, $leechers, $completed));
