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;
<?
//
// 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);
<?
/*
Switch-Torrents Webseed/HTTPseed Generator - April 1, 2021
Implements Torrent signing
Implements "GetRight" style HTTP/FTP seeding
-> transmission-create
-> ut-signing-tool
Version 1.0.1 (April 2, 2021):
- CLI: Single-quoted command parameters (transmission-create) to be on safe side
- Process: Updated temporary torrent filename with md5 hash to avoid iteration processing conflicts (file overlapping)
- Process: Update torrent database row with +1 unchoked seed
- Process: Get release version from filename [v0.0.0]
Version 1.0.2 (April 4, 2021):
- Process: Category INT value by file extension type
- Process: Determine DLC by dictionary path array keys: [0][1]
*/
require_once '../site.php';
require_once '../classes/class.bencoding.php';
$db->connect();
site_header();
error_reporting(E_ALL);
$dir = new DirectoryIterator('webseeds/');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$passkey = 'YOUR_PASSKEY'; // default passkey
$tmpname = md5('webseed') . '.torrent'; // temporary filename
exec("transmission-create -o 'webseeds/$tmpname' -p 1 -c '$CONFIG[site_title]' -s 1024 -t '$CONFIG[base_url_nossl]/announce?passkey=$passkey' 'webseeds/$fileinfo'", $result);
print_r($result);
$fp = fopen('webseeds/' . $tmpname, 'rb');
$data = '';
while (!feof($fp)) {
$data .= fread($fp, 8192);
}
fclose($fp);
$arr = bdecode($data);
$infobc = bencode($arr['info']);
if ($infobc === false) {
$db->query_params('INSERT INTO log (added, txt) VALUES(NOW(), :log)', array(
'log' => 'Webseed: Bencoding error'
));
}
// Get release version
$version = str_replace(']' . substr($fileinfo, -4, strpos($fileinfo, '.')), '', substr(strstr($fileinfo, '[v'), 2));
// Determine DLC included
if ($arr !== false && array_key_exists('files', $arr['info'])) {
foreach ($arr['info']['files'] as $file) {
if (array_key_exists('path', $file)) {
$dlc = false;
if (str_contains($file['path'][0], 'DLC') || str_contains($file['path'][1], 'DLC')) { // PHP 8
$dlc = true;
}
}
// Determine category by file extension - PHP 8
if (str_contains($file['path'][0], 'xci')) {
$category = 47;
} else if (str_contains($file['path'][0], 'nsz')) {
$category = 48;
} else if (str_contains($file['path'][0], 'nsp')) {
$category = 1;
}
}
}
// Generate info hash
$info_hash = sha1($infobc);
$total_size = 0;
if (array_key_exists('files', $arr['info'])) {
foreach ($arr['info']['files'] as $file) {
if (array_key_exists('length', $file)) {
$total_size += $file['length'];
}
}
} else if (array_key_exists('length', $arr['info'])) {
$total_size += $arr['info']['length'];
}
// Check duplicate info hash
$res = $db->query_params('SELECT torrent_id FROM torrents WHERE info_hash = :info_hash', array(
'info_hash' => $info_hash
));
if ($row = $res->fetch()) {
continue;
}
// BEP 19 - WebSeed - HTTP/FTP Seeding (GetRight style)
if ($fileinfo->isFile()) {
$arr['url-list'] = sprintf('%s/webseeds/%s', $CONFIG['base_url_nossl'], $fileinfo); // single file
} else if ($fileinfo->isDir()) {
$arr['url-list'] = sprintf('%s/webseeds/%s/', $CONFIG['base_url_nossl'], substr($fileinfo, 0, strpos($fileinfo, '.'))); // multi-file
}
// BEP 25 - Torrent Signing
sign_torrent($fileinfo, 0, bencode($arr));
$data = file_get_contents('../signing/signed.torrent');
// Save to database
$torrent_id = $db->query_params('INSERT INTO torrents (user_id, name, descr, webseed, anon, info_hash, size, tags, version, dlc, youtube, freeleech, cover1, image1, image2, category, cert_signed) VALUES (:user_id, :name, :description, :webseed, :anonymous, :info_hash, :total_size, :tags, :version, :dlc, :youtube, :freeleech, :cover1, :image1, :image2, :category, :cert_signed)', array(
'user_id' => 1,
'name' => substr($fileinfo, 0, strpos($fileinfo, '.')),
'description' => substr($fileinfo, 0, strpos($fileinfo, '.')),
'webseed' => 1,
'anonymous' => 0,
'info_hash' => $info_hash,
'total_size' => $total_size,
'tags' => 'Webseed, Auto',
'version' => $version,
'dlc' => ($dlc ? 'Yes' : 'No'),
'youtube' => '',
'freeleech' => 0,
'cover1' => 'switch_cover_none.png',
'image1' => 'nocover.png',
'image2' => 'nocover.png',
'category' => intval($category),
'cert_signed' => 'signed'
), 'torrent_id') or die('Error inserting webseed torrent');
$db->query_params('INSERT INTO torrents_blob (torrent_id, user_id, data) VALUES (:last_id, :user_id, :data)', array(
'last_id' => $torrent_id,
'data' => $data,
'user_id' => 1
));
if ($torrent_id) {
$db->query_params('INSERT INTO log (added, txt) VALUES(NOW(), :log)', array(
'log' => sprintf("Webseed imported \"%s\" ID: %s", $fileinfo, $torrent_id)
));
// Update torrent with 1 unchoked seed
$db->query_params('UPDATE torrents SET seeders = 1 WHERE torrent_id = :torrent_id', array(
'torrent_id' => $torrent_id
));
// Remove temporary file
unlink('webseeds/' . $tmpname);
break; // testing this
}
}
}
site_footer();
<?
interface Store
{
public function checkbonus($user_id);
public function rowtype(int $user_id, array $data);
public function retrieveitems($res);
public function updateuser($user_id);
}
class DB
{
public $pdo;
public function __construct()
{
$dsn = "mysql:host=$host;dbname=$db;port=$port;charset=utf8mb4";
try {
$this->pdo = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e) {
$this->log_exception($e->getMessage(), $e->getLine());
}
}
private function log_exception($msg, $line)
{
$query = "INSERT INTO sql_logging(exception, added) VALUES(?, NOW())";
$stt = $this->pdo->prepare($query);
$stt->bindValue(1, $msg . $line);
$stt->execute();
}
public function preprocess($query, $get_id)
{
return $query;
}
public function write_log($text)
{
$this->query_params('INSERT INTO log (added, txt) VALUES(NOW(), :log)', array(
'log' => $text
));
}
public function interval($s)
{
return sprintf("INTERVAL '%s'", $s);
}
public function query_params($query, $params = null, $get_id = null)
{
if (is_null($params)) {
$params = array();
}
try {
$query = $this->preprocess($query, $get_id);
$stmt = $this->pdo->prepare($query);
foreach ($params as $key => $param) {
if ($key == "data") {
$stmt->bindValue(':' . $key, $param, PDO::PARAM_LOB);
} else if ($key == "limit") {
$stmt->bindValue(':' . $key, (int) trim($param), PDO::PARAM_INT);
} else {
$stmt->bindValue(':' . $key, $param);
}
}
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if (is_null($get_id)) {
return $stmt;
} else {
return $this->get_last_id($stmt, $get_id);
}
}
catch (PDOException $e) {
$this->log_exception($e->getMessage(), $e->getLine());
}
}
}
class Seedbonus extends DB implements Store
{
public function __construct($db = 'database', $username = 'username', $password = 'password', $host = 'localhost', $port = 3306, $options = [])
{
$this->invite = true;
$this->traffic = true;
$this->hnr = true;
$this->slots = true;
$this->vip = true;
$this->last_exchange = true;
$this->value = true;
$this->feature = true;
}
public function checkbonus($user_id)
{
$points = $this->query_params('SELECT users.seedbonus, users.username, users.class, users.user_id, bonus.cost, bonus.descr, bonus.type, bonus.value FROM users, bonus WHERE users.user_id = :user_id', array(
'user_id' => $user_id
)) or die('db error');
while ($check = $points->fetch()) {
$pointsuser = $check['user_id'];
$currentpoints = $check['seedbonus'];
if ($currentpoints) {
return true;
}
}
return false;
}
public function retrieveitems($res)
{
$res = $this->query_params('SELECT * FROM bonus ORDER BY type');
}
public function rowtype(int $user_id, array $data)
{
$this->query_params('SELECT users.seedbonus, users.perk_avatar, users.username, users.slots, users.last_exchange, users.class, users.user_id, bonus.cost, bonus.descr, bonus.type, bonus.value, bonus.id FROM users, bonus WHERE users.user_id = :user_id AND bonus.id = :post_id', array(
'user_id' => $user_id,
'post_id' => $data['id']
));
return $row = $res->fetch();
if ($row['type'] == $this->invite && $data['id'] == $row['id']) {
$this->query_params('UPDATE users SET invites = invites + :value WHERE user_id = :user_id', array(
'value' => $row['value'],
'user_id' => $user_id
));
return sprintf('Your account has been <b>credited</b> for <b>%s</b> Extra Invites!', $row['value']);
}
}
public function updateuser($user_id)
{
$res = $this->query_params('SELECT users.seedbonus, users.perk_avatar, users.username, users.slots, users.last_exchange, users.class, users.user_id, bonus.cost, bonus.descr, bonus.type, bonus.value, bonus.id FROM users, bonus WHERE users.user_id = :user_id AND bonus.id = :post_id', array(
'user_id' => $user_id,
'post_id' => $data['id']
));
$row = $res->fetch();
$this->query_params('UPDATE users SET seedbonus = seedbonus - :cost WHERE user_id = :user_id', array(
'cost' => $row['cost'],
'user_id' => $user_id
));
}
}