BETA6 - announce.php
Changes:
- Fake-Ratio check (recoded/improved)
- Code clean up
- Added webseeder (partial)
- Now relies on verified upload/download speeds (ratio-fake check, happy hour - beta7)
- Replaced OpenSSL token auth with Base64 (reliability/compatibility)
- Added detection/handling for "limited" users
Next/Coming:
- "Happy Hour" speeds / stats
- Further speed checks against unrealistic announce intervals (1.5mbps / 5mbps)
- Freeleech support
- Extended checks on user and data bonuses based on community rep.
- Global traffic logging (account/community index)
Changes:
- Fake-Ratio check (recoded/improved)
- Code clean up
- Added webseeder (partial)
- Now relies on verified upload/download speeds (ratio-fake check, happy hour - beta7)
- Replaced OpenSSL token auth with Base64 (reliability/compatibility)
- Added detection/handling for "limited" users
Next/Coming:
- "Happy Hour" speeds / stats
- Further speed checks against unrealistic announce intervals (1.5mbps / 5mbps)
- Freeleech support
- Extended checks on user and data bonuses based on community rep.
- Global traffic logging (account/community index)
<?
require_once '../site.php';
require_once '../bencoding.php';
$db->connect();
$db->query_params('DELETE FROM peers WHERE last_announce + ' . $db->interval('1 hour') . ' < CURRENT_TIMESTAMP');
header('Content-Type: text/plain');
function fail($reason) {
die(bencode(array('failure reason' => $reason)));
}
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;
}
// Check Peer ID if banned - Sep 5, 2020
function isPeerIDBanned($peer_id, $torrent_id, $passkey)
{
global $db, $CONFIG;
if (array_key_exists('ban_peer_ids', $CONFIG)) {
$valid = $db->query_params('SELECT chosen_peer_id, torrent_id, passkey FROM peers WHERE torrent_id = :torrent_id AND passkey = :passkey', array('torrent_id' => $torrent_id,'passkey' => $passkey)) or fail('db error');
foreach ($CONFIG as $key) {
foreach ($valid as $peer) {
if ($CONFIG['ban_peer_ids'] == $peer['chosen_peer_id']) {
$message = sprintf('Peer ID banned - %s', $peer['chosen_peer_id']);
$db->query_params('INSERT INTO announcelogs (message) VALUES (:message)', array('message' => $message)); // Log the event
fail(sprintf('Peer ID banned - %s', $peer['chosen_peer_id']));
}
}
}
} else {
return;
}
}
function isConnectable($ip, $port) {
$fp = @fsockopen($ip, $port, $errno, $errstr, 0.1);
if (!$fp) {
return false;
} else {
fclose($fp);
return true;
}
}
$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
);
$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 or not
$seeder = ($data['left'] == 0) ? 'yes' : 'no';
// Web seeder - Oct 18, 2020 - peers.webseed
$webseeder = ((isset($data['webseeder']) && $data['webseeder'] == 'yes' && $seeder == 'yes') ? 'yes' : 'no');
// Get client info
$client = substr($data['peer_id'], 0, 8);
$connect = isConnectable($data['ip'], $data['port']);
if ($connect) {
$connectable = 'yes';
}else{
$connectable = 'no';
}
$data['info_hash'] = bin2hex($data['info_hash']);
$data['peer_id'] = bin2hex($data['peer_id']);
// Token authentication - Oct 4, 2020 - Decode token hash => substitute string order => verify passkey => auth peer/user
if ($data['passkey']) {
$passkey = $data['passkey']; // legacy
}else{
$passkey = substr(base64_decode($data['token'], true), 11, strlen(substr(base64_decode($data['token'], true), 12)));
}
$res = $db->query_params('SELECT slots, user_id, passkey, username, class, limited FROM users WHERE passkey = :passkey', array('passkey' => $passkey));
$user_row = $res->fetch() or fail('Token authentication failed.');
// Check limited user - Oct 18, 2020
if ($user_row['limited'] == 'yes') fail('Account is limited. Sign in to resolve.');
// Verify token hash - Oct 5, 2020
if ($data['token']) {
if (!hash_equals($user_row['passkey'], $passkey)) {
fail('Token is invalid');
}
}
// Max Slots - Fixed - Seedbox-Compatible - Sep 21, 2020
$maxslots = $db->query_params("SELECT COUNT(DISTINCT torrent_id) AS total, last_announce FROM peers WHERE user_id = :user_id AND seeder = 'no'", array('user_id' => $user_row['user_id']));
$current = $maxslots->fetch();
if ($current['total'] > $user_row['slots']) {
$checklast = $db->query_params('SELECT user, date, message FROM shoutbox WHERE user = :username', array('username' => $user_row['username']));
$lastmessage = $checklast->fetch();
if ($lastmessage['date'] < $current['last_announce']) {
$event = "[url=$CONFIG[base_url]/user/?id=$user_row[user_id] ] $user_row[username][/url] reached their maximum download slot $current[total]/$user_row[slots]";
$reason = "You have reached your max download slots of 4 (out of 3 available). You can visit Seed Bonus to upgrade to more slots.";
$db->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array('receiver' => $user_row['username'], 'event' => $event));
$db->query_params("INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES (0, :user_id, NOW(), :reason, 0, 'Max Download Slots Reached')", array('user_id' => $user_row['user_id'], 'reason' => $reason)); // Sep 23, 2020
}
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) {
if (array_key_exists($key, $_SERVER)) {
$potential_ip = trim(explode(',', $_SERVER[$key])[0]);
// Ignore private IP addresses
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->query_params('SELECT torrent_id FROM torrents WHERE info_hash = :info_hash', array('info_hash' => $data['info_hash'])) or fail('db error');
$torrent_row = $res->fetch() or fail('no such torrent');
// Ratio-faker tool check - Oct 18, 2020
$interval = time() - $current['last_announce'];
if ($interval == 0) $interval = 1;
$downloaded = $data['downloaded'];
$uploaded = $data['uploaded'];
// If speed is higher than 4 MB/sec, the user is 'cheating'. Frustrate user by adding their desired upload to their download
if (($uploaded / $interval) > 4194304) { // 4194304 - 4MB/Sec
$event = "[url=$CONFIG[base_url]/user/?id=$user_row[user_id] ] $user_row[username][/url] used Ratiofaker-Tool - Event 1: " . $data['uploaded'] . " Upload @ " . ($data['uploaded'] / $interval) . "/sec Fake Rate";
$db->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array('receiver' => $user_row['username'], 'event' => $event));
fail('Ratiofaker-Tool detected.');
// Add upload as download and zero out upload for event
$downloaded += $uploaded;
$uploaded = 0;
}
$valid = $db->query_params('SELECT * FROM peers WHERE torrent_id = :torrent_id AND passkey = :passkey', array('torrent_id' => $torrent_row['torrent_id'], 'passkey' => $data['passkey'])) or fail('db error');
$active = $valid->fetch();
$res = $db->query_params('SELECT peer_id, completed, seeder FROM peers WHERE user_id = :user_id AND torrent_id = :torrent_id AND chosen_peer_id = :chosen_peer_id', array('user_id' => $user_row['user_id'], 'torrent_id' => $torrent_row['torrent_id'], 'chosen_peer_id' => $data['peer_id'])) or fail('db error');
if (!($peer_row = $res->fetch())) {
isPeerIDBanned($peer_row['peer_id'], $torrent_row['torrent_id'], $data['passkey']);
$res = $db->query_params('INSERT INTO peers (started, passkey, connectable, user_id, torrent_id, chosen_peer_id, ip, port, client) VALUES (now(), :passkey, :connectable, :user_id, :torrent_id, :chosen_peer_id, :ip, :port, :client)', array('passkey' => $data['passkey'], 'connectable' => $connectable, 'user_id' => $user_row['user_id'], 'torrent_id' => $torrent_row['torrent_id'], 'chosen_peer_id' => $data['peer_id'], 'ip' => $data['ip'], 'port' => $data['port'], 'client' => $client), 'peer_id') or fail('Cant insert peer.');
$peer_row = array('peer_id' => $res);
$db->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array('uploaded' => $uploaded, 'downloaded' => $downloaded, 'user_id' => $user_row['user_id']));
} else {
isPeerIDBanned($peer_row['peer_id'], $torrent_row['torrent_id'], $data['passkey']);
$db->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array('uploaded' => $uploaded, 'downloaded' => $downloaded, 'user_id' => $user_row['user_id']));
$db->query_params('UPDATE peers SET connectable = :connectable, to_go = :to_go, uploaded = :uploaded, downloaded = :downloaded, seeder = :seeder, client = :client, ip = :ip, port = :port, last_announce = CURRENT_TIMESTAMP WHERE peer_id = :peer_id', array('connectable' => $connectable, 'to_go' => $data['left'], 'uploaded' => $uploaded, 'downloaded' => $downloaded, 'seeder' => $seeder, 'client' => $client, 'ip' => $data['ip'], 'port' => $data['port'], 'peer_id' => $peer_row['peer_id'])) or fail('db error');
}
if (array_key_exists('left', $data)) {
$db->query_params('UPDATE peers SET completed = :completed, seeder = :seeder WHERE peer_id = :peer_id', array('completed' => $db->encode_bool($data['left'] === 0), 'seeder' => $seeder, 'peer_id' => $peer_row['peer_id']));
}
if ($data['event'] === 'stopped') {
$db->query_params('DELETE FROM peers WHERE peer_id = :peer_id', array('peer_id' => $peer_row['peer_id']));
}
if ($data['event'] === 'completed') {
$db->query_params('DELETE FROM peers WHERE peer_id = :peer_id', array('peer_id' => $peer_row['peer_id']));
$db->query_params('UPDATE torrents SET times_completed = times_completed + :completed WHERE torrent_id = :torrent_id', array('completed' => $db->encode_bool($data['left'] === 0), 'torrent_id' => $torrent_row['torrent_id'])); // Added Sep 9, 2020
}
$res = $db->query_params('SELECT count(nullif(completed,false)) AS complete, count(nullif(completed,true)) AS incomplete FROM peers WHERE torrent_id = :torrent_id', array('torrent_id' => $torrent_row['torrent_id'])) or fail('db error');
$comp_res = $res->fetch() or fail('db error');
$output = array(
'interval' => 30 * 60,
'complete' => intval($comp_res['complete']),
'incomplete' => intval($comp_res['incomplete']),
'peers' => array(),
);
$res = $db->query_params('SELECT chosen_peer_id, ip, port FROM peers WHERE torrent_id = :torrent_id AND peer_id != :peer_id ORDER BY ' . $db->random() . ' LIMIT :limit', array('torrent_id' => $torrent_row['torrent_id'], 'peer_id' => $peer_row['peer_id'], 'limit' => $data['numwant'])) or fail('db error');
while ($row = $res->fetch()) {
$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;
}
}
echo bencode($output);