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
User Posts

Go to Profile

Semi final version of the rewritten and greatly improved announce.php script I use in high volume traffic/peers. This can be ported if you use PDO very easily. Many days have gone into extensive testing and client testing side by side, and database queries to confirm accuracy with every query line. In queries/prepared statements, change torrent_id and user_id to just id

This file performs really well and is very lightweight and secure. Enjoy.

Semi-Final / September

Next in final script:

- FakeRatio Check / ban
- Client banning
- Traffic Stats => new table
- Additional config options across for better control over sections of logic

NOTE: You will need your db class and "bencoding.php" from the BETA2 zip.


<?
require_once 'bencoding.php';
$db->connect(); // Replace with your db class object/instance

$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;
}

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 avail_slots($user_id, $user_class)
{
   global $db;
   $checkslots = $db->query_params('SELECT u.class, u.warned, u.user_id, g.group_id, g.level, g.maxslots AS totalslots FROM groups g LEFT JOIN users u ON u.class = g.group_id WHERE g.group_id = :user_class AND u.user_id = :user_id', array('user_class' => $user_class, 'user_id' => $user_id));
   $row = $checkslots->fetch();
   if (array_key_exists('warned', $row)) {
       if ($row['warned'] == 'yes'): $maxslot = 1; else: $maxslot = $row['maxslots']; endif;
       return $row['totalslots'];
   }
}

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' => true,
   '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));
   }
}

// Get client info
$client = substr($data['peer_id'], 0, 8);

$data['info_hash'] = bin2hex($data['info_hash']);
$data['peer_id'] = bin2hex($data['peer_id']);

$res = $db->query_params('SELECT user_id, passkey, username, class FROM users WHERE passkey = :passkey', array('passkey' => $data['passkey'])) or fail('db error line 56');
$user_row = $res->fetch() or fail("access denied line 57");

// Max download slots check - Sep 5, 2020
$maxslots = $db->query_params("SELECT COUNT(DISTINCT torrent_id) AS total FROM peers WHERE user_id = :user_id AND seeder = 'no'", array('user_id' => $user_row['user_id']));
foreach ($maxslots as $slots) {
   $totalslots = $slots['total'];
   $maxslot = avail_slots($user_row['user_id'], $user_row['class']);
   if ($totalslots >= $maxslot){ // removed >= as it was reducing downloads by only 1 at a time (2/2, 1 downloading) transfer for regular class.
       fail("Maximum $totalslots/$maxslot download slots exceeded! Finish current transfers to reclaim slots.");
   }
}

// TODO: Deal with tokens / config
if (array_key_exists('token', $data)) {
   $token = md5('token{' . $data['torrent_id'] . ',' . $user_row['passkey'] . '}');
   if (!hash_equals($token, $data['token'])) fail('access denied line 67');
}

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;
}

$seeder = ($data['left'] == 0) ? 'yes' : 'no';

if (isConnectable($data['ip'], $data['port'])): $connectable = 'yes'; else: $connectable = 'no'; endif;

$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');


$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);
   // BEGIN user upload/download stats
   $db->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array('uploaded' => $data['uploaded'], 'downloaded' => $data['downloaded'], 'user_id' => $user_row['user_id']));

} else {

   isPeerIDBanned($peer_row['peer_id'], $torrent_row['torrent_id'], $data['passkey']);
   // BEGIN user upload/download stats
   $db->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array('uploaded' => $data['uploaded'], 'downloaded' => $data['downloaded'], 'user_id' => $user_row['user_id']));
   // END user upload/download stats
   $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' => $data['uploaded'], 'downloaded' => $data['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']));
}

// Completed - work
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);
Anyways, see the PM about token hashes. It’s a very real problem with passkey leaking. I wonder how many if not all are effected?

my announce

$token = md5('token{' . $data['torrent_id'] . ',' . $user_row['passkey'] . '}');
if (!hash_equals($token, $data['token'])) fail('access denied');
Other Languages — 2020-09-12 00:16:16 in M-BiTsy Support
Did you get to do the language class?
Say Thanks & Force — 2020-09-12 00:11:55 in v3 Mods Completed
"MicroMonkey, post: 69345, member: 311":

seems like if more than 1 user thanks, then it wont display class color of each user....hmmm. What to do about that now.....


Loop the row results and define the array. This is done using while or preferably, and slower.. foreach. Then that iterates the row results and provides ability to do anything to it.
Edit: So I have the class and code set, now there are two functions that trigger the interval check/clean so i just have on my index this

require 'classes/class.cleanup.php';
$cleanup = new Cleanup();
$cleanup->run();

Will this be fine? I had issues with the start_clean() function, it never automatically worked like before.
Enchanced Requests — 2020-09-08 02:08:03 in v3 Mods Completed
Ne devrait pas parler de parition. Pouvez-vous utiliser un client SQL sur un ordinateur?
-
Should not be talking about parition. Can you use SQL client on computer?
Enchanced Requests — 2020-09-07 04:52:28 in v3 Mods Completed
Assign a default value with a condition, or use SQL client or phpmyadmin and set a default value of 0
Good to hear. In any case, your description is always
$varname['descr']
so tracing that is always useful when things go hairy. :)
Code Journel — 2020-09-05 18:19:00 in Support & Suggestions
Here is the code journal. Here I will post with a heading, what i've improved/fixed and will supply code. This makes a great place to reference back, without 20 documents riddled through the hard drive lol

-------

I got tired of looking at avail_slots() how it was so I made better, with the db class of course.


// Max Slots
function avail_slots($user_id, $user_class)
{
   global $db;
   $checkslots  = $db->query_params('SELECT u.class, u.user_id, g.group_id, g.level, g.maxslots FROM groups g LEFT JOIN users u ON u.class = g.group_id WHERE g.group_id = :user_class', array('user_class' => $user_class));
   $row  = $checkslots->fetch();
   if (array_key_exists('warned', $row)) { // does the column exist?
       if ($row['warned'] == 'yes'): $maxslot = 1; else: $maxslot = $row['maxslots']; endif;
       return $maxslot;
   }
}

And the main function to check this. I also cleaned this up and tested on a naked page impersonating my secondary account for accuracy.

$maxslots = $db->query_params("SELECT COUNT(DISTINCT torrent_id) AS total FROM peers WHERE user_id = :user_id AND seeder = 'no'", array('user_id' => $user_row['user_id']));
foreach ($maxslots as $slots)
   $totalslots = $slots['total'];
   $maxslot = avail_slots($user_row['user_id'], $user_row['class']);
   if ($totalslots >= $maxslot) fail("Maximum $totalslots/$maxslot download slots exceeded! Finish current transfers to reclaim slots.");

The secret here is making use of SQL properly and utilizing JOINS when needed. No need to call on 2 queries. I didn't bother doing a join-less query as that just complicates testing.
-------

Pager. Counting total torrent row results in a slim fashion. pager() picks up on count value to generate the 0,1 LIMIT. My JS now reads this variable, and old pager is removed indefinitely.

$countdb = $db->query_params('SELECT COUNT(torrent_id) FROM torrents');
   foreach ($countdb->fetch() as $total) $count = $total;


And we have [color=rgb(226, 80, 65)]$count[/color]

-------

Cleaning up Cleanup lol and adding better checks, removing the silly INT gmtime value and using DATETIME in place.


function autoclean()
{
   global $db, $CONFIG;
   require_once '../cleanup.php';
   $clean_time = $db->query_params("SELECT last_time FROM tasks WHERE task='cleanup'");
   $clean      = $clean_time->fetch();
   $last_time  = $clean['last_time'];
 
   if (empty($clean)) $db->query_params("INSERT INTO tasks (task, last_time) VALUES ('cleanup', now())"); return;
   if ($last_time + $CONFIG['autoclean_interval'] < date()) return;
       $planned_clean = $db->query_params("UPDATE tasks SET last_time = now() WHERE task='cleanup' AND last_time = :last_time", array('now' => $last_time));
   if (!empty($planned_clean)) return;
 
   do_cleanup();
}


-------

Messages. As I've taken a try at a working type, its not built right. So redoing with a message class, using this query I found on stackoverflow

SELECT CONCAT(GREATEST(sender,receiver)," ",LEAST(sender,receiver)) AS thread, MAX(CONCAT(added,"|",msg)) as added, MAX(added) AS last_message, messages.* FROM messages WHERE receiver= 1 GROUP BY added ORDER BY added DESC


Threaded messages. Both IDs between both sender and receiver are there if query run for (receiver = 1) - 1 = admin (very first account)

So thats a good step for messages and gets all one needs.
Database Error — 2020-09-05 13:38:42 in v3 Support
"niki, post: 69318, member: 20338":

thank you storrent2020 for your help but I don't see where to put the code ????:rolleyes:



torrents-upload.php

<?php
require_once("backend/functions.php");
dbconn();

// check access and rights
if ($site_config["MEMBERSONLY"]){
   loggedinonly();

   if($CURUSER["can_upload"]=="no")
       show_error_msg(T_("ERROR"), T_("UPLOAD_NO_PERMISSION"), 1);
   if ($site_config["UPLOADERSONLY"] && $CURUSER["class"] < 4)
       show_error_msg(T_("ERROR"), T_("UPLOAD_ONLY_FOR_UPLOADERS"), 1);
}

$announce_urls = explode(",", strtolower($site_config["announce_list"]));  //generate announce_urls[] from config.php

if ($_POST["takeupload"] == "yes") {
   require_once("backend/parse.php");

   // Check form data.
   if ( ! isset($_POST['type'], $_POST['name'], $_FILES['torrent']) )
         $message = T_('MISSING_FORM_DATA');

   if (($num = $_FILES['torrent']['error']))
        show_error_msg(T_('ERROR'), T_("UPLOAD_ERR[$num]"), 1);

   $f = $_FILES["torrent"];
   $fname = $f["name"];

   if (empty($fname))
       $message = T_("EMPTY_FILENAME");

   $nfo = 'no';
   
   if ($_FILES['nfo']['size'] != 0) {
       $nfofile = $_FILES['nfo'];

       if ($nfofile['name'] == '')
           $message = T_("NO_NFO_UPLOADED");
       
       if (!preg_match('/^(.+)\.nfo$/si', $nfofile['name'], $fmatches))
           $message = T_("UPLOAD_NOT_NFO");

       if ($nfofile['size'] == 0)
           $message = T_("NO_NFO_SIZE");

       if ($nfofile['size'] > 65535)
           $message = T_("NFO_UPLOAD_SIZE");

       $nfofilename = $nfofile['tmp_name'];

       if (($num = $_FILES['nfo']['error']))
            $message = T_("UPLOAD_ERR[$num]");
   
       $nfo = 'yes';
   }

   $descr = $_POST["descr"];

   if (!$descr)
       $descr = T_("UPLOAD_NO_DESC");

   $langid = (int) $_POST["lang"];

   /*if (!is_valid_id($langid))
       $message = "Please be sure to select a torrent language";*/

   $catid = (int) $_POST["type"];

   if (!is_valid_id($catid))
       $message = T_("UPLOAD_NO_CAT");

   if (!validfilename($fname))
       $message = T_("UPLOAD_INVALID_FILENAME");

   if (!preg_match('/^(.+)\.torrent$/si', $fname, $matches))
       $message = T_("UPLOAD_INVALID_FILENAME_NOT_TORRENT");

       $shortfname = $torrent = $matches[1];

   if (!empty($_POST["name"]))
       $name = $_POST["name"];
   
   $tmpname = $f['tmp_name'];

   //end check form data

   if (!$message) {
   //parse torrent file
   $torrent_dir = $site_config["torrent_dir"];
   $nfo_dir = $site_config["nfo_dir"];

   //if(!copy($f, "$torrent_dir/$fname"))
   if(!move_uploaded_file($tmpname, "$torrent_dir/$fname"))
       show_error_msg(T_("ERROR"), T_("ERROR"). ": " . T_("UPLOAD_COULD_NOT_BE_COPIED")." $tmpname - $torrent_dir - $fname",1);

   $TorrentInfo = array();
   $TorrentInfo = ParseTorrent("$torrent_dir/$fname");


   $announce = $TorrentInfo[0];
   $infohash = $TorrentInfo[1];
   $creationdate = $TorrentInfo[2];
   $internalname = $TorrentInfo[3];
   $torrentsize = $TorrentInfo[4];
   $filecount = $TorrentInfo[5];
   $annlist = $TorrentInfo[6];
   $comment = $TorrentInfo[7];
   $filelist = $TorrentInfo[8];

/*
//for debug...
   print ("<br /><br />announce: ".$announce."");
   print ("<br /><br />infohash: ".$infohash."");
   print ("<br /><br />creationdate: ".$creationdate."");
   print ("<br /><br />internalname: ".$internalname."");
   print ("<br /><br />torrentsize: ".$torrentsize."");
   print ("<br /><br />filecount: ".$filecount."");
   print ("<br /><br />annlist: ".$annlist."");
   print ("<br /><br />comment: ".$comment."");
*/

   //check announce url is local or external
   if (!in_array($announce, $announce_urls, 1)){
       $external='yes';
   }else{
       $external='no';
   }

   //if externals is turned off
   if (!$site_config["ALLOWEXTERNAL"] && $external == 'yes')
       $message = T_("UPLOAD_NO_TRACKER_ANNOUNCE");
   }
   if ($message) {
       @unlink("$torrent_dir/$fname");
       @unlink($tmpname);
       @unlink("$nfo_dir/$nfofilename");
       show_error_msg(T_("UPLOAD_FAILED"), $message,1);
   }

   //release name check and adjust
   if ($name ==""){
       $name = $internalname;
   }
   $name = str_replace(".torrent","",$name);
   $name = str_replace("_", " ", $name);

   //upload images
   $allowed_types = &$site_config["allowed_image_types"];

   $inames = array();
   for ($x=0; $x < 2; $x++) {
       if (!($_FILES['image'.$x]['name'] == "")) {
           $y = $x + 1;

           //if (!preg_match('/^(.+)\.(jpg|gif|png)$/si', $_FILES[image.$x]['name']))
           //    show_error_msg(T_("INVAILD_IMAGE"), T_("THIS_FILETYPE_NOT_IMAGE"), 1);

           if ($_FILES['image$x']['size'] > $site_config['image_max_filesize'])
               show_error_msg(T_("ERROR"), T_("INVAILD_FILE_SIZE_IMAGE"), 1);

           $uploaddir = $site_config["torrent_dir"]."/images/";

           $ifile = $_FILES['image'.$x]['tmp_name'];

           $im = getimagesize($ifile);

           if (!$im[2])
               show_error_msg(T_("ERROR"), sprintf(T_("INVALID_IMAGE"), $y), 1);

           if (!array_key_exists($im['mime'], $allowed_types))
               show_error_msg(T_("ERROR"), T_("INVALID_FILETYPE_IMAGE"), 1);

           $ret = SQL_Query_exec("SHOW TABLE STATUS LIKE 'torrents'");
           $row = mysqli_fetch_array($ret);
           $next_id = $row['Auto_increment'];

           $ifilename = $next_id . $x . $allowed_types[$im['mime']];

           $copy = copy($ifile, $uploaddir.$ifilename);

           if (!$copy)
               show_error_msg(T_("ERROR"), sprintf(T_("IMAGE_UPLOAD_FAILED"), $y), 1);

           $inames[] = $ifilename;

       }

   }
   //end upload images

   //anonymous upload
   $anonyupload = $_POST["anonycheck"];
   if ($anonyupload == "yes") {
       $anon = "yes";
   }else{
       $anon = "no";
   }






$filecounts = (int) $filecount;
$ret = SQL_Query_exec("INSERT INTO torrents (filename, owner, name, descr, image1, image2, category, added, info_hash, size, numfiles, save_as, announce, external, nfo, torrentlang, anon, last_action, allocine) VALUES (".sqlesc($fname).", '".$CURUSER['id']."', ".sqlesc($name).", ".sqlesc($descr).", '".$inames[0]."', '".$inames[1]."', '".$catid."', '" . get_date_time() . "', '".$infohash."', '".$torrentsize."', '".$filecount."', ".sqlesc($fname).", '".$announce."', '".$external."', '".$nfo."', '".$langid."','$anon', '".get_date_time()."', ".sqlesc($_POST['allocine']).")");




   $id = mysqli_insert_id($GLOBALS["DBconnector"]);

   if (mysqli_errno($GLOBALS["DBconnector"]) == 1062)
       show_error_msg(T_("UPLOAD_FAILED"), T_("UPLOAD_ALREADY_UPLOADED"), 1);

   //Update the members uploaded torrent count
   /*if ($ret){
       SQL_Query_exec("UPDATE users SET torrents = torrents + 1 WHERE id = $userid");*/
   
   if($id == 0){
       unlink("$torrent_dir/$fname");
       $message = T_("UPLOAD_NO_ID");
       show_error_msg(T_("UPLOAD_FAILED"), $message, 1);
   }

   rename("$torrent_dir/$fname", "$torrent_dir/$id.torrent");

   if (is_array($filelist) && count($filelist)) {
       foreach ($filelist as $file) {
           $dir = '';
           $size = $file["length"];
           $count = count($file["path"]);
           for ($i=0; $i<$count;$i++) {
               if (($i+1) == $count)
                   $fname = $dir.$file["path"][$i];
               else
                   $dir .= $file["path"][$i]."/";
           }



           SQL_Query_exec("INSERT INTO `files` (`torrent`, `path`, `filesize`) VALUES($id, ".sqlesc($fname).", $size)");
       }
   } else {
       SQL_Query_exec("INSERT INTO `files` (`torrent`, `path`, `filesize`) VALUES($id, ".sqlesc($TorrentInfo[3]).", $torrentsize)");
   }

   if (!is_array($annlist)) {
       $annlist = array(array($announce));
   }
   foreach ($annlist as $ann) {
       foreach ($ann as $val) {
           if (strtolower(substr($val, 0, 4)) != "udp:") {
               SQL_Query_exec("INSERT INTO `announce` (`torrent`, `url`) VALUES($id, ".sqlesc($val).")");
           }
       }
   }

   if ($nfo == 'yes') {
           move_uploaded_file($nfofilename, "$nfo_dir/$id.nfo");
   }

   //EXTERNAL SCRAPE


   if ($external=='yes' && $site_config['UPLOADSCRAPE']){
       $tracker=str_replace("/announce","/scrape",$announce);
       $stats             = torrent_scrape_url($tracker, $infohash);
       $seeders         = (int) strip_tags($stats['seeds']);
       $leechers         = (int) strip_tags($stats['peers']);
       $downloaded     = (int) strip_tags($stats['downloaded']);

       SQL_Query_exec("UPDATE torrents SET leechers='".$leechers."', seeders='".$seeders."',times_completed='".$downloaded."',last_action= '".get_date_time()."',visible='yes' WHERE id='".$id."'");
   }
   //END SCRAPE

   write_log( sprintf(T_("TORRENT_UPLOADED"), htmlspecialchars($name), $CURUSER["username"]) );

   //Uploaded ok message (update later)
   if ($external=='no')
       $message = sprintf( T_("TORRENT_UPLOAD_LOCAL"), $name, $id, $id );
   else
       $message = sprintf( T_("TORRENT_UPLOAD_EXTERNAL"), $name, $id );
   show_error_msg(T_("UPLOAD_COMPLETE"), $message, 1);

   die();
}//takeupload


///////////////////// FORMAT PAGE ////////////////////////

stdhead(T_("UPLOAD"));

begin_frame(T_("UPLOAD_RULES"));
   echo "<b>".stripslashes($site_config["UPLOADRULES"])."</b>";
   echo "<br />";
end_frame();

begin_frame(T_("UPLOAD"));
?>
<form name="upload" enctype="multipart/form-data" action="torrents-upload.php" method="post">
<input type="hidden" name="takeupload" value="yes" />
<table border="0" cellspacing="0" cellpadding="6" align="center">
<?php
print ("<tr><td align='right' valign='top'>" . T_("ANNOUNCE_URL") . ": </td><td align='left'>");

while (list($key,$value) = thisEach($announce_urls)) {
   echo "<b>$value</b><br />";
}

if ($site_config["ALLOWEXTERNAL"]){
   echo "<br /><b>".T_("THIS_SITE_ACCEPTS_EXTERNAL")."</b>";
}
print ("</td></tr>");
print ("<tr><td align='right'>" . T_("TORRENT_FILE") . ": </td><td align='left'> <input type='file' name='torrent' size='50' value='" . $_FILES['torrent']['name'] . "' />\n</td></tr>");
print ("<tr><td align='right'>" .T_("NFO"). ": </td><td align='left'> <input type='file' name='nfo' size='50' value='" . $_FILES['nfo']['name'] . "' /><br />\n</td></tr>");
print ("<tr><td align='right'>" . T_("TORRENT_NAME") . ": </td><td align='left'><input type='text' name='name' size='60' value='" . $_POST['name'] . "' /><br />".T_("THIS_WILL_BE_TAKEN_TORRENT")." \n</td></tr>");
print ("<tr><td colspan='2' align='center'>".T_("MAX_FILE_SIZE").": ".mksize($site_config['image_max_filesize'])."<br />".T_("ACCEPTED_FORMATS").": ".implode(", ", array_unique($site_config["allowed_image_types"]))."<br /></td></tr><tr><td align='right'>".T_("IMAGE")." 1:&nbsp;&nbsp;</td><td><input type='file' name='image0' size='50' /></td></tr><tr><td align='right'>".T_("IMAGE")." 2:&nbsp;&nbsp;</td><td><input type='file' name='image1' size='50' /></td></tr>");

$category = "<select name=\"type\">\n<option value=\"0\">" . T_("CHOOSE_ONE") . "</option>\n";

$cats = genrelist();
foreach ($cats as $row)
   $category .= "<option value=\"" . $row["id"] . "\">" . htmlspecialchars($row["parent_cat"]) . ": " . htmlspecialchars($row["name"]) . "</option>\n";

$category .= "</select>\n";
print ("<tr><td align='right'>" . T_("CATEGORY") . ": </td><td align='left'>".$category."</td></tr>");


$language = "<select name=\"lang\">\n<option value=\"0\">".T_("UNKNOWN_NA")."</option>\n";

$langs = langlist();
foreach ($langs as $row)
   $language .= "<option value=\"" . $row["id"] . "\">" . htmlspecialchars($row["name"]) . "</option>\n";

$language .= "</select>\n";
print ("<tr><td align='right'>".T_("LANGUAGE").": </td><td align='left'>".$language."</td></tr>");

if ($site_config['ANONYMOUSUPLOAD'] && $site_config["MEMBERSONLY"] ){ ?>
   <tr><td align="right"><?php echo T_("UPLOAD_ANONY");?>: </td><td><?php printf("<input name='anonycheck' value='yes' type='radio' " . ($anonycheck ? " checked='checked'" : "") . " />".T_("YES")." <input name='anonycheck' value='no' type='radio' " . (!$anonycheck ? " checked='checked'" : "") . " />".T_("NO").""); ?> &nbsp;<i><?php echo T_("UPLOAD_ANONY_MSG");?></i>
   </td></tr>
   <?php
}

print ("<tr><td align='center' colspan='2'>" . T_("DESCRIPTION") . "</td></tr></table>");

require_once("backend/bbcode.php");
print textbbcode("upload","descr","$descr");
?>

<br /><br /><center><input type="submit" value="<?php echo T_("UPLOAD_TORRENT"); ?>" /><br />
<i><?php echo T_("CLICK_ONCE_IMAGE");?></i>
</center>
</form>

<?php
end_frame();
stdfoot();
?>



No problem. So you want to replace:

$filecounts = (int) $filecount;
$ret = SQL_Query_exec("INSERT INTO torrents (filename, owner, name, descr, image1, image2, category, added, info_hash, size, numfiles, save_as, announce, external, nfo, torrentlang, anon, last_action, allocine) VALUES (".sqlesc($fname).", '".$CURUSER['id']."', ".sqlesc($name).", ".sqlesc($descr).", '".$inames[0]."', '".$inames[1]."', '".$catid."', '" . get_date_time() . "', '".$infohash."', '".$torrentsize."', '".$filecount."', ".sqlesc($fname).", '".$announce."', '".$external."', '".$nfo."', '".$langid."','$anon', '".get_date_time()."', ".sqlesc($_POST['allocine']).")");

with this

if (in_array('path', $TorrentInfo)) {
   $filecount = $TorrentInfo[5];
}else{
   $filecount = intval(0);
}
$ret = SQL_Query_exec("INSERT INTO torrents (filename, owner, name, descr, image1, image2, category, added, info_hash, size, numfiles, save_as, announce, external, nfo, torrentlang, anon, last_action, allocine) VALUES (".sqlesc($fname).", '".$CURUSER['id']."', ".sqlesc($name).", ".sqlesc($descr).", '".$inames[0]."', '".$inames[1]."', '".$catid."', '" . get_date_time() . "', '".$infohash."', '".$torrentsize."', '".$filecount."', ".sqlesc($fname).", '".$announce."', '".$external."', '".$nfo."', '".$langid."','$anon', '".get_date_time()."', ".sqlesc($_POST['allocine']).")");


see what that does.
Database Error — 2020-09-05 11:15:02 in v3 Support
There is literally no conditions taking place. So try replacing variable with this:


if (in_array('path', $TorrentInfo)) {
   $filecounts = $TorrentInfo[5];
}else{
   $filecounts = intval(0);
}


Or...

if (array_key_exists('path', $TorrentInfo)) {
   $filecounts = $TorrentInfo[5];
else{
   $filecounts = intval(0);
}


if that fails, then there is a problem with $filecount variable, and it is not returning a INT value for you, and because that column is of NOT NULL, it will never let you get past. Now you can go into your database, and ALLOW NULL on that column, and you will push through but that won't help your issue.

This is calling on decoding to read the 'path' array data in the .torrent

$filecount = $TorrentInfo[color=rgb(235, 107, 86)][5][/color];

[color=rgb(235, 107, 86)]5[/color] = the 5th array key (which is the file list) - you know its an array when you see [] or array(). Those hold useful keys we check or retrieve.

So whats happening, is its not retrieving that key. That would be assumed to be a bad .torrent file, or the bdecode class is failing to decode and pass to database.


   $announce = $TorrentInfo[0];
   $infohash = $TorrentInfo[1];
   $creationdate = $TorrentInfo[2];
   $internalname = $TorrentInfo[3];
   $torrentsize = $TorrentInfo[4];
   $filecount = $TorrentInfo[5];
   $annlist = $TorrentInfo[6];
   $comment = $TorrentInfo[7];
   $filelist = $TorrentInfo[8];


From key 0 - 8, each key is returning something about the data decoded from your torrents. 5 is failing. We know its file count.
Thanks for asking niki, I have actually improved this code and extended it with more data to show, including private yes/no, announce urls etc. I will update post.

Readers: When posting this code, I did not yet have the rude awakening of multiple database crashes (good thing for InnoDB), turns out storing BLOB data in the same torrent table is horrible practice (all those connections / seek time), and will put the server to its knee's (for me 4 hours after sleep).

The solution is creating another table with relational link to the primary torrent table and referencing back ONLY the to the data column. I'll explain as I write the post. I use the blob data daily, no issues now. But that is important to know. Huge oversight.
Sounds like a socket limitation first thoughts, now worst case is the client is screwing up. No client is truly stable given the protocol specifications and limitations.

Passkeys are completely insecure, and allows anyone to leech them off from other sites (ghost peers). Look at the token code. That is the answer (md5 hashes torrent_id and passkey together).

Thing is, how can you use two? Your row only holds one key, and it’s confirming that by the info_hash in the table, then your off to peer swarm. I see conflict with2 keys even in testing.
This is probably why they decided on “connection limit”, to avoid error, not so much “control the concurrent access”.

Unless I’m missing something, would expect my own codebase to do the same.
Post updated with final code for a perfect working migrator. This is 100% safe and can be dropped in anytime to your root /

- Detect private or external torrent by bdecoded data
- Removed any handling of info_hash (very important)

torrents-details.php

You can read file list, sizes and much more! Using this code and including the class if you haven't already

be sure to include `data` in your main query in torrents-details - near top ( torrents.name, torrents.descr, etc ... torrents.data, )

print("<table align='center' cellpadding='0' cellspacing='0' border='0' width='100%'><tr><th class='table_head' align='left'>File</th><th width='50' class='table_head'>Size</th></tr></table>");
$data = $row['data'];
$arr  = bdecode($data);
if ($arr !== false && array_key_exists('info', $arr)) {
   if (array_key_exists('files', $arr['info'])) {
       foreach ($arr['info']['files'] as $file) {
           if (array_key_exists('path', $file)) {
               printf("<span>%s</span>", implode('/', $file['path']));
               printf("<br/>");
           }
}
   } else if (array_key_exists('name', $arr['info'])) {
       printf("<span>%s</span>", $arr['info']['name']);
       printf("<br/>");
   }
}
Snatchlist [TTv3] — 2020-09-01 22:14:14 in v3 Mods Completed
I’m adding today with Max slots
"m-jay, post: 69270, member: 20288":

Php should not have ?> at the end to close files it's bad practice


I haven't used closing tag in weeks, easier to read too. You'll notice any php editor will turn on syntax highlighting as soon as you type ?> - also when pasting code without a closing tag
"m-jay, post: 69256, member: 20288":

Once tested I will add update sql  (y)  old passwords of md5 will not work at the minute we use bycrypt
In full release all css & html will be in templates so easier for those with skills


Take rehashing from my account class. It’s great.
Snatchlist [TTv3] — 2020-08-31 11:33:27 in v3 Mods Completed
I'll tackle this on a night. It looks hellish lol
Snatchlist [TTv3] — 2020-08-31 10:28:20 in v3 Mods Completed
Bump up the date column(s) after. Then should be immediate effect.

I would use strtotime() and wrap the expected results => update column then trigger the desired results.

UPDATE snatched SET date_field = " . strtotime(-48 hour') ." WHERE id = X
Snatchlist [TTv3] — 2020-08-31 01:11:12 in v3 Mods Completed
"Propaganda, post: 69248, member: 60":

hnr = hit and run, meaning snatched and not seeded and data back.


Thanks [USER=60]@Propaganda[/USER] that is all I need to know ?
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: 3
  • Members: 0
  • Guests online: 3
  • Comments: 3
  • Messages: 1,728