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
New TTv3 Announce (mysqli)
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / Torrent Trader / v3 Mods in Progress

2021-04-11 03:06:48
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

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);
class.mysqli.php
File missing
Last edited by STorrents2020 on 2021-04-19 01:03:05
2021-04-11 05:06:00
First release
New TTv3 Announce.zip
File missing
2021-04-11 14:05:32
hmm, not working for me. might be the $db connection part
TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
Last edited by MicroMonkey on 2021-04-11 14:34:39
2021-04-12 14:02:34
Hard to say, can you point your browser to that file and tell me what it says? Be sure to turn on error_reporting(E_ALL).
2021-04-12 22:05:29
I got this
Fatal error: Uncaught Exception: Unable to do prepared statement: DELETE FROM peers WHERE last_announce + INTERVAL 1 hour < CURRENT_TIMESTAMP in /var/www/site.com/backend/classes/class.mysqli.php:81 Stack trace: #0 /var/www/site.com/announcetest.php(21): DatabaseClass->Remove() #1 {main} thrown in /var/www/site.com/backend/classes/class.mysqli.php on line 81
TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
2021-04-13 14:13:28
Remove that line and let me know
2021-04-14 00:04:56
new output after deleting only line 81, function left intact. I understand that some of this error may be beacuse I am not actually using this file, Im only testing it. I did not overwrite my actual announce file. I renamed it and tested. I can test it live if needed
d14:failure reason23:missing key: downloadede
TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
Last edited by MicroMonkey on 2021-04-14 00:06:43
2021-04-15 14:15:59
Looks good! So missing keys is because the client is asking for those and not the browser.

Looks to be working. You should be good to go.
2021-04-17 16:25:55
#1 ..M8 MicroMonkey  :D


2021-04-17 16:56:14
I can confirm that this "MOD" converted to V 2.0.8 and "normal" mysql works on a "live" server works quite correctly, so far so good


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
2021-04-17 18:33:54
oops, speak too fast, after more than 30 minutes around, my torrent is red and sharing, thank you for the help

no SQL error or the .torrent
Last edited by spiritblue on 2021-04-17 18:34:35
2021-04-17 19:59:46
I am the same. I cannot make it work for me. unsure why. It appears to work, but then stops.
TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
2021-04-17 20:39:57
Quote:
oops, speak too fast, after more than 30 minutes around, my torrent is red and sharing, thank you for the help

no SQL error or the .torrent


Sorry, same here   :(


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
2021-04-18 02:05:20
Can anyone see failure message in the tracker message (utorrent tracker tab for example)?

it sends failure message out to client if something triggers fail()

Its possible a few functions I have in there are being called, that are not included in announce.php

I'll take a look over
2021-04-18 14:20:23
only thing that qbit said was "not working" on my end. I do see some tables in there that dont exist in my version of TT. That could be killing it since it wouldnt be able to move past it, such as chosen_peer_id. Im a bit hung over so thats all I could see right now lol.
TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
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