Advertisement
Underworld1337

Untitled

Sep 17th, 2014
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.65 KB | None | 0 0
  1. <?
  2.  
  3. ob_start("ob_gzhandler");
  4.  
  5. require_once("include/bittorrent.php");
  6. require_once("include/benc.php");
  7.  
  8. hit_start();
  9.  
  10. function hex2bin($hexdata) {
  11.  
  12.    for ($i=0;$i<strlen($hexdata);$i+=2) {
  13.      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
  14.    }
  15.  
  16.    return $bindata;
  17. }
  18.  
  19. function err($msg)
  20. {
  21.     benc_resp(array("failure reason" => array(type => "string", value => $msg)));
  22.     hit_end();
  23.     exit();
  24. }
  25.  
  26. function benc_resp($d)
  27. {
  28.     benc_resp_raw(benc(array(type => "dictionary", value => $d)));
  29. }
  30.  
  31. function benc_resp_raw($x)
  32. {
  33.     header("Content-Type: text/plain");
  34.     header("Pragma: no-cache");
  35.     print($x);
  36. }
  37.  
  38. function check_ip_limit() {
  39.     global $userid;
  40.  
  41.     // Check IP limit
  42.     $res = mysql_query("SELECT DISTINCT(ip) AS ip FROM peers WHERE userid=$userid");
  43.     $count = 0;
  44.     $found = FALSE;
  45.     while ($row = mysql_fetch_assoc($res)) {
  46.         $count++;
  47.         if ($row["ip"] == $ip) {
  48.             $found = TRUE;
  49.             break;
  50.         }
  51.     }
  52.    
  53.     if (!$found && $count >= $GLOBALS["MAX_PASSKEY_IPS"])
  54.         err("Zu viele unterschiedliche IPs fuer diesen Benutzer (max ".$GLOBALS["MAX_PASSKEY_IPS"].")");
  55. }
  56.  
  57. if (in_array($_SERVER["HTTP_USER_AGENT"], $GLOBALS["BAN_USERAGENTS"]))
  58.     err("Du benutzt einen gebannten Client. Bitte lies die FAQ!");
  59.  
  60. $req = "info_hash:peer_id:!ip:port:uploaded:downloaded:left:!event";
  61. if ($GLOBALS["CLIENT_AUTH"] == CLIENT_AUTH_PASSKEY) {
  62.     if ($GLOBALS["PASSKEY_SOURCE"] == PASSKEY_USE_PARAM) {
  63.         $req .= ":passkey";
  64.         // Using announce.php?passkey={KEY} will lead to an incorrect parameter list,
  65.         // so the first parameter appended by the client gets appended to the passkey parameter.
  66.         // This match will extract the parameter to $_GET
  67.         if (preg_match("/^([a-f0-9]{16})\\?(.*?)\\=(.*)$/is", $_GET["passkey"], $m)) {
  68.             $_GET["passkey"] = $m[1];
  69.             $_GET[$m[2]] = $m[3];
  70.         }
  71.     }
  72.     if ($GLOBALS["PASSKEY_SOURCE"] == PASSKEY_USE_SUBDOMAIN) {
  73.         preg_match("/^([a-f0-9]{16})\\./i", $_SERVER["HTTP_HOST"], $m);
  74.         if (strlen($m[1])==16)
  75.             $passkey = $m[1];
  76.         else
  77.             err("Fehlender Parameter fuer Announce: passkey");
  78.     }
  79. }
  80.  
  81. foreach (explode(":", $req) as $x)
  82. {
  83.     if ($x[0] == "!")
  84.     {
  85.         $x = substr($x, 1);
  86.         $opt = 1;
  87.     }
  88.     else
  89.         $opt = 0;
  90.     if (!isset($_GET[$x]))
  91.     {
  92.         if (!$opt)
  93.             err("Fehlender Parameter fuer Announce: $x");
  94.         continue;
  95.     }
  96.     $GLOBALS[$x] = unesc($_GET[$x]);
  97. }
  98.  
  99. foreach (array("info_hash","peer_id") as $x)
  100. {
  101.     if (strlen($GLOBALS[$x]) != 20)
  102.         err("Ungueltiger Wert fuer $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
  103. }
  104.  
  105. foreach ($GLOBALS["BAN_PEERIDS"] as $banned_id)
  106. {
  107.     if (substr($GLOBALS["peer_id"],0,strlen($banned_id)) == $banned_id)
  108.         err("Du benutzt einen gebannten Client. Bitte lies das FAQ!");
  109. }
  110.  
  111. $ip = getip();
  112. $origip = $ip;
  113. $port = 0 + $port;
  114. $origport = $port;
  115. $downloaded = 0 + $downloaded;
  116. $uploaded = 0 + $uploaded;
  117. $left = 0 + $left;
  118.  
  119. $rsize = 50;
  120. foreach(array("num want", "numwant", "num_want") as $k)
  121. {
  122.     if (isset($_GET[$k]))
  123.     {
  124.         $rsize = 0 + $_GET[$k];
  125.         break;
  126.     }
  127. }
  128.  
  129. $agent = $_SERVER["HTTP_USER_AGENT"];
  130.  
  131. // Deny access made with a browser...
  132. if (ereg("^Mozilla\\/", $agent) || ereg("^Opera\\/", $agent) || ereg("^Links ", $agent) || ereg("^Lynx\\/", $agent))
  133.     err("Dieser Torrent ist dem Tracker nicht bekannt");
  134.  
  135. if (!$port || $port > 0xffff)
  136.     err("Ungueltiges TCP-Port");
  137.  
  138. if (!isset($event))
  139.     $event = "";
  140.  
  141. $seeder = ($left == 0) ? "yes" : "no";
  142.  
  143. dbconn(false);
  144.  
  145. hit_count();
  146.  
  147. $res = mysql_query("SELECT id, name, category, banned, activated, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts FROM torrents WHERE " . hash_where("info_hash", $info_hash));
  148.  
  149. $torrent = mysql_fetch_assoc($res);
  150. if (!$torrent)
  151.     err("Dieser Torrent ist dem Tracker nicht bekannt");
  152.  
  153. if ($torrent["activated"] != "yes")
  154.     err("Dieser Torrent ist dem Tracker nicht bekannt");
  155.  
  156. $torrentid = $torrent["id"];
  157.  
  158. $fields = "seeder, peer_id, ip, port, uploaded, downloaded, userid";
  159.  
  160. $numpeers = $torrent["numpeers"];
  161. $limit = "";
  162. if ($numpeers > $rsize)
  163.     $limit = "ORDER BY RAND() LIMIT $rsize";
  164. $res = mysql_query("SELECT $fields FROM peers WHERE torrent = $torrentid AND connectable = 'yes' $limit");
  165.  
  166. $resp = "d" . benc_str("interval") . "i" . $GLOBALS["ANNOUNCE_INTERVAL"] . "e" . benc_str("peers") . "l";
  167. unset($self);
  168. while ($row = mysql_fetch_assoc($res))
  169. {
  170.     $row["peer_id"] = hash_pad($row["peer_id"]);
  171.  
  172.     if ($row["peer_id"] === $peer_id)
  173.     {
  174.         $userid = $row["userid"];
  175.         $self = $row;
  176.         continue;
  177.     }
  178.  
  179.     $resp .= "d" .
  180.         benc_str("ip") . benc_str($row["ip"]) .
  181.         benc_str("peer id") . benc_str($row["peer_id"]) .
  182.         benc_str("port") . "i" . $row["port"] . "e" .
  183.         "e";
  184. }
  185.  
  186. $resp .= "ee";
  187.  
  188. $selfwhere = "torrent = $torrentid AND " . hash_where("peer_id", $peer_id);
  189.  
  190. if (!isset($self))
  191. {
  192.     $res = mysql_query("SELECT $fields FROM peers WHERE $selfwhere");
  193.     $row = mysql_fetch_assoc($res);
  194.     if ($row)
  195.     {
  196.         $userid = $row["userid"];
  197.        
  198.         $self = $row;
  199.     }
  200. }
  201.  
  202.  
  203. //// Up/down stats ////////////////////////////////////////////////////////////
  204.  
  205. if (!isset($self))
  206. {
  207.     if ($GLOBALS["CLIENT_AUTH"] == CLIENT_AUTH_PASSKEY) {
  208.         $rz = mysql_query("SELECT id, uploaded, downloaded, class, tlimitseeds, tlimitleeches, tlimitall FROM users WHERE passkey=".sqlesc(hex2bin($passkey))." AND enabled = 'yes' ORDER BY last_access DESC LIMIT 1") or err("Tracker error 2");
  209.         if ($MEMBERSONLY && mysql_num_rows($rz) == 0)
  210.             err("Ungueltiger PassKey. Lies das FAQ!");
  211.     } else {
  212.         $rz = mysql_query("SELECT id, uploaded, downloaded, class, tlimitseeds, tlimitleeches, tlimitall FROM users WHERE ip=".sqlesc($ip)." AND enabled = 'yes' ORDER BY last_access DESC LIMIT 1") or err("Tracker error 2");
  213.         if ($MEMBERSONLY && mysql_num_rows($rz) == 0)
  214.             err("Unbekannte IP. Lies das FAQ!");
  215.     }
  216.    
  217.     $az = mysql_fetch_assoc($rz);
  218.     $userid = $az["id"];
  219.  
  220.     // Wartezeit prรผfen
  221.     $wait = get_wait_time($az["id"], $torrentid, FALSE, $left);
  222.     if (($left > 0 || !$GLOBALS["ONLY_LEECHERS_WAIT"]) && $wait)
  223.         err("Wartezeit (noch " . ($wait) . "h) - Bitte lies das FAQ!");
  224.    
  225.     // Torrent-Limit prรผfen
  226.     // $az["tlimitall"] < 0 entspricht unlimitiert!
  227.     if ($az["tlimitall"] >= 0) {
  228.         $arr = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS cnt FROM peers WHERE userid=$userid"));
  229.         $numtorrents = $arr["cnt"];
  230.         $arr = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS cnt FROM peers WHERE userid=$userid AND seeder='yes'"));
  231.         $seeds = $arr["cnt"];
  232.         $leeches = $numtorrents - $seeds;
  233.         $limit = get_torrent_limits($az);
  234.  
  235.         if (   ($limit["total"] > 0)
  236.             &&(($numtorrents >= $limit["total"])
  237.             || ($left == 0 && $seeds >= $limit["seeds"])
  238.             || ($left > 0 && $leeches >= $limit["leeches"])))
  239.                 err("Maximales Torrent-Limit erreicht ($limit[seeds] Seeds, $limit[leeches] Leeches, $limit[total] Gesamt)");
  240.        
  241.     }
  242.    
  243.     check_ip_limit();
  244.    
  245.     // Create traffic log entry if not existent
  246.     $res = mysql_query("SELECT * FROM `traffic` WHERE `userid`=$userid AND `torrentid`=$torrentid");
  247.     if (@mysql_num_rows($res) == 0)
  248.         mysql_query("INSERT INTO `traffic` (`userid`,`torrentid`) VALUES ($userid, $torrentid)");
  249. }
  250. else
  251. {
  252.     // We won't check the IP again, since this would disrupt a user's download if he
  253.     // uses another IP to continue browsing on the tracker.
  254.     if ($GLOBALS["CLIENT_AUTH"] == CLIENT_AUTH_PASSKEY) {
  255.         $res = mysql_query("SELECT passkey,id FROM users WHERE id=$userid AND enabled = 'yes'");
  256.         $pkrow = mysql_fetch_assoc($res);
  257.         $passkey = hex2bin($passkey);
  258.         if ($passkey != $pkrow["passkey"])
  259.             err("Ungueltiger PassKey. Lies das FAQ!");
  260.            
  261.         check_ip_limit();
  262.     }
  263.    
  264.     $upthis = max(0, $uploaded - $self["uploaded"]);
  265.     $downthis = max(0, $downloaded - $self["downloaded"]);
  266.  
  267.     $arr = mysql_fetch_assoc(mysql_query("SELECT UNIX_TIMESTAMP(last_action) AS lastaction FROM peers WHERE $selfwhere"));
  268.     $interval = time() - $arr["lastaction"];
  269.    
  270.     if ($interval == 0) $interval = 1;
  271.  
  272.     // If speed is higher than 4 MB/sec, the user is apparently cheating.
  273.     // Frustrate him by adding his desired upload to his download ^^
  274.     if (($upthis / $interval) > $GLOBALS["RATIOFAKER_THRESH"]) {
  275.         // Write mod comment
  276.         write_modcomment($userid, 0, "announce.php: Ratiofaker-Tool verwendet: ".mksize($upthis)." Upload, Fake Rate: ".mksize($upthis / $interval)."/sek");
  277.        
  278.         // Add upload as download and zero out upload.
  279.         $downthis += $upthis;
  280.         $upthis = 0;
  281.     }
  282.  
  283.     if ($upthis > 0 || $downthis > 0) {
  284.         // Update traffic for current torrent
  285.         if ($self["seeder"] == "yes")
  286.             mysql_query("UPDATE `traffic` SET `downloaded`=`downloaded`+$downthis, `uploaded`=`uploaded`+$upthis, `uploadtime`=`uploadtime`+$interval WHERE `userid`=$userid AND `torrentid`=$torrentid");
  287.         else
  288.             mysql_query("UPDATE `traffic` SET `downloaded`=`downloaded`+$downthis, `uploaded`=`uploaded`+$upthis, `downloadtime`=`downloadtime`+$interval,`uploadtime`=`uploadtime`+$interval WHERE `userid`=$userid AND `torrentid`=$torrentid");
  289.         mysql_query("UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error 3");
  290.     }
  291. }
  292.  
  293. // Bad user? If yes, we'll provide him with an invalid peer list :)
  294. $acctdata = mysql_fetch_assoc(mysql_query("SELECT baduser FROM accounts WHERE userid=$userid"));
  295. if ($acctdata["baduser"]==1) {
  296.     $resarr = bdec($resp);
  297.     for ($I=0; $I<count($resarr["value"]["peers"]["value"]); $I++) {
  298.         $tmpip = $resarr["value"]["peers"]["value"][$I]["value"]["ip"]["value"];
  299.         $resarr["value"]["peers"]["value"][$I]["value"]["port"]["value"] += mt_rand(100,250);
  300.        
  301.         $rndnum = mt_rand(1,254);
  302.         $resarr["value"]["peers"]["value"][$I]["value"]["ip"]["value"] =
  303.             preg_replace("/\\.(\\d{1,3})$/", ".$rndnum", $tmpip);
  304.        
  305.     }
  306.     $resp = benc($resarr);
  307.    
  308.     $rndnum = mt_rand(1,254);
  309.     $ip = preg_replace("/\\.(\\d{1,3})$/", ".$rndnum", $ip);
  310.     $port += mt_rand(100,250);
  311.    
  312. }
  313.  
  314.  
  315. ///////////////////////////////////////////////////////////////////////////////
  316.  
  317. function portblacklisted($port)
  318. {
  319.     // direct connect
  320.     if ($port >= 411 && $port <= 413) return true;
  321.  
  322.     // bittorrent
  323.     if ($port >= 6881 && $port <= 6889) return true;
  324.  
  325.     // kazaa
  326.     if ($port == 1214) return true;
  327.  
  328.     // gnutella
  329.     if ($port >= 6346 && $port <= 6347) return true;
  330.  
  331.     // emule
  332.     if ($port == 4662) return true;
  333.  
  334.     // winmx
  335.     if ($port == 6699) return true;
  336.  
  337.     return false;
  338. }
  339.  
  340. $updateset = array();
  341.  
  342. if ($event == "stopped")
  343. {
  344.     if (isset($self))
  345.     {
  346.         mysql_query("DELETE FROM peers WHERE $selfwhere");
  347.         if (mysql_affected_rows())
  348.         {
  349.             if ($self["seeder"] == "yes")
  350.                 $updateset[] = "seeders = seeders - 1";
  351.             else
  352.                 $updateset[] = "leechers = leechers - 1";
  353.         }
  354.     }
  355.     mysql_query("INSERT INTO startstoplog (userid,event,`datetime`,torrent,ip,peerid,useragent) VALUES ($userid,'stop',NOW(),$torrentid,".sqlesc($_SERVER["REMOTE_ADDR"]).",".sqlesc($peer_id).",".sqlesc($agent).")");
  356.    
  357.     $announcedelay = @mysql_fetch_assoc(@mysql_query("SELECT * FROM `announcedelay` WHERE `peer_id`=".sqlesc($peer_id)));
  358.     if (is_array($announcedelay)) {
  359.         if ($announcedelay["first"] && $announcedelay["second"] && $announcedelay["quantity"]) {
  360.             $duration1 = $announcedelay["second"]-$announcedelay["first"];
  361.             $duration2 = time() - $announcedelay["second"];
  362.             if ($duration1 < 310 && $duration2 < 10 && $uploaded - $announcedelay["quantity"] == 0) {
  363.                 write_modcomment($userid, 0, "announce.php: Evtl. Ratiomaker 0.5+ benutzt: ".mksize($uploaded)." Upload / ".mksize($downloaded)." Download, Fake Rate: ".mksize($uploaded / $duration1)."/sek, Delays: {$duration1}s / {$duration2}s");
  364.             }
  365.         }
  366.     }
  367.    
  368.     $resp = benc_resp(array("failure reason" => array(type => "string", value => "Kein Fehler - Torrent gestoppt.")));
  369. }
  370. else
  371. {
  372.     if ($event == "completed") {
  373.         $updateset[] = "times_completed = times_completed + 1";
  374.         mysql_query("INSERT INTO completed (user_id, torrent_id, torrent_name, torrent_category, complete_time) VALUES ($userid, $torrentid, ".sqlesc($torrent["name"]).", ".$torrent["category"].", NOW())");
  375.     }
  376.    
  377.     if (isset($self))
  378.     {
  379.         $announcedelay = @mysql_fetch_assoc(@mysql_query("SELECT * FROM `announcedelay` WHERE `peer_id`=".sqlesc($peer_id)));
  380.         if (is_array($announcedelay)) {
  381.             if ($announcedelay["second"] == 0)
  382.                 mysql_query("UPDATE `announcedelay` SET `second`=UNIX_TIMESTAMP(),`quantity`=$uploaded WHERE `peer_id`=".sqlesc($peer_id));
  383.         }
  384.        
  385.         mysql_query("UPDATE peers SET uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = NOW(), seeder = '$seeder'"
  386.             . ($seeder == "yes" && $self["seeder"] != $seeder ? ", finishedat = " . time() : "") . " WHERE $selfwhere");
  387.         if (mysql_affected_rows() && $self["seeder"] != $seeder)
  388.         {
  389.             if ($seeder == "yes")
  390.             {
  391.                 $updateset[] = "seeders = seeders + 1";
  392.                 $updateset[] = "leechers = leechers - 1";
  393.             }
  394.             else
  395.             {
  396.                 $updateset[] = "seeders = seeders - 1";
  397.                 $updateset[] = "leechers = leechers + 1";
  398.             }
  399.         }
  400.     }
  401.     else
  402.     {
  403.         if (portblacklisted($origport))
  404.             err("Der TCP-Port $origport ist nicht erlaubt.");
  405.         else
  406.         {
  407.             $sockres = @fsockopen($origip, $origport, $errno, $errstr, 5);
  408.             if (!$sockres)
  409.                 $connectable = "no";
  410.             else
  411.             {
  412.                 $connectable = "yes";
  413.                 @fclose($sockres);
  414.             }
  415.         }
  416.  
  417.         $ret = mysql_query("INSERT INTO peers (connectable, torrent, peer_id, ip, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, agent, uploadoffset, downloadoffset) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", $port, $uploaded, $downloaded, $left, NOW(), NOW(), '$seeder', $userid, " . sqlesc($agent) . ", $uploaded, $downloaded)");
  418.         if ($ret)
  419.         {
  420.             if ($seeder == "yes")
  421.                 $updateset[] = "seeders = seeders + 1";
  422.             else
  423.                 $updateset[] = "leechers = leechers + 1";
  424.         }
  425.         mysql_query("INSERT INTO startstoplog (userid,event,`datetime`,torrent,ip,peerid,useragent) VALUES ($userid,'start',NOW(),$torrentid,".sqlesc($_SERVER["REMOTE_ADDR"]).",".sqlesc($peer_id).",".sqlesc($agent).")");
  426.         mysql_query("INSERT INTO announcedelay (peer_id, first) VALUES (".sqlesc($peer_id).", UNIX_TIMESTAMP())");
  427.         mysql_query("DELETE FROM announcedelay WHERE `first`<UNIX_TIMESTAMP()-900");
  428.     }
  429. }
  430.  
  431. if ($seeder == "yes")
  432. {
  433.     if ($torrent["banned"] != "yes")
  434.         $updateset[] = "visible = 'yes'";
  435.     $updateset[] = "last_action = NOW()";
  436. }
  437.  
  438. if (count($updateset))
  439.     mysql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = $torrentid");
  440.  
  441. benc_resp_raw($resp);
  442.  
  443. hit_end();
  444.  
  445. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement