-
Notifications
You must be signed in to change notification settings - Fork 7
/
announce.php
805 lines (685 loc) · 32.4 KB
/
announce.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
<?php
/////////////////////////////////////////////////////////////////////////////////////
// xbtit - Bittorrent tracker/frontend
//
// Copyright (C) 2004 - 2019 Btiteam
//
// This file is part of xbtit.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
////////////////////////////////////////////////////////////////////////////////////
ignore_user_abort(1);
$GLOBALS['peer_id'] = '';
$summaryupdate = [];
$BASEPATH = __DIR__;
require "$BASEPATH/include/config.php";
require "$BASEPATH/include/common.php";
error_reporting(E_ALL ^ E_NOTICE);
// check if we are using standard php tracker or xbtt backend
// if using xbbt we will make a redirect to xbtt announce using
// informations given in config + pid if private
// thank you petr1fied for the code.
global $XBTT_USE;
if ($XBTT_USE) {
function implode_with_keys($glue, $array)
{
$output = [];
foreach ($array as $key => $item) {
$output[] = $key.'='.$item;
}
return implode($glue, $output);
}
if (isset($_GET['pid'])) {
$pid = $_GET['pid'];
if (strpos($pid, '?') !== false) {
$pid = substr($pid, 0, strpos($pid, '?'));
}
unset($_GET['pid']);
} else {
$pid = '';
}
if (isset($_SERVER['QUERY_STRING'])) {
$query_string = substr($_SERVER['QUERY_STRING'], strpos($_SERVER['QUERY_STRING'], '?') + 1);
} else {
$query_string = implode_with_keys('&', $_GET);
}
if ($pid != '') { // private announce
header("Location: $XBTT_URL/$pid/announce?".$query_string);
} else { // public
header("Location: $XBTT_URL/announce?".$query_string);
}
exit;
}
// not using xbtt, let us go ;)
// Schedules an update to the table. It gets so much traffic
// that we do all our changes at once.
// When called, the column $column for the current info_hash is incremented
// by $value, or set to exactly $value if $abs is true.
function summaryAdd($column, $value, $abs = false)
{
if (isset($GLOBALS['summaryupdate'][$column])) {
if (!$abs) {
$GLOBALS['summaryupdate'][$column][0] += $value;
} else {
show_error('Tracker bug calling summaryAdd');
}
} else {
$GLOBALS['summaryupdate'][$column][0] = $value;
$GLOBALS['summaryupdate'][$column][1] = $abs;
}
}
// connect to db
if ($GLOBALS['persist']) {
$conres = ($GLOBALS['conn'] = mysqli_connect($dbhost, $dbuser, $dbpass)) or show_error('Tracker error - mysql_connect: '.((is_object($GLOBALS['conn'])) ? mysqli_error($GLOBALS['conn']) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
} else {
$conres = ($GLOBALS['conn'] = mysqli_connect($dbhost, $dbuser, $dbpass)) or show_error('Tracker error - mysql_connect: '.((is_object($GLOBALS['conn'])) ? mysqli_error($GLOBALS['conn']) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
((bool) mysqli_query($GLOBALS['conn'], "USE $database")) or show_error("Tracker error - $database - ".((is_object($GLOBALS['conn'])) ? mysqli_error($GLOBALS['conn']) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
// connection is done ok
if (isset($_GET['pid'])) {
$pid = $_GET['pid'];
} else {
$pid = '';
}
if (strpos($pid, '?')) {
$tmp = substr($pid, strpos($pid, '?'));
$pid = substr($pid, 0, strpos($pid, '?'));
$tmpname = substr($tmp, 1, strpos($tmp, '=') - 1);
$tmpvalue = substr($tmp, strpos($tmp, '=') + 1);
$_GET[$tmpname] = $tmpvalue;
}
// Many thanks to KktoMx for figuring out this head-ache causer,
// and to bideomex for showing me how to do it PROPERLY... :)
if (get_magic_quotes_gpc()) {
$info_hash = bin2hex(stripslashes($_GET['info_hash']));
$peer_id = bin2hex(stripslashes($_GET['peer_id']));
} else {
$info_hash = bin2hex($_GET['info_hash']);
$peer_id = bin2hex($_GET['peer_id']);
}
$sp_compact = isset($_GET['compact']) ? true : false;
$iscompact = $sp_compact ? (bool)(0 + $_GET['compact'] == '1') : false;
// controll if client can handle gzip
if ($GZIP_ENABLED) {
if (stristr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && extension_loaded('zlib') && ini_get('zlib.output_compression') == 0) {
if (ini_get('output_handler') != 'ob_gzhandler' && !$iscompact) {
// only for non compact
ob_start('ob_gzhandler');
} else {
ob_start();
}
} else {
ob_start();
}
}
// end gzip controll
header('Content-type: text/plain');
header('Pragma: no-cache');
// Error: no web browsers allowed
$agent = mysqli_real_escape_string($GLOBALS['conn'], $_SERVER['HTTP_USER_AGENT']);
// Deny access made with a browser...
if (stripos($agent, 'Mozilla') !== false || stripos($agent, 'Opera') !== false || stripos($agent, 'Links') !== false || stripos($agent, 'Lynx') !== false || stripos($agent, 'Wget') !== false || strpos($peer_id, 'OP') === 0) {
header('HTTP/1.0 500 Bad Request');
die("This a a bittorrent application and can't be loaded into a browser");
}
// check if al needed information is sent by the client
if (!isset($_GET['port']) || !isset($_GET['downloaded']) || !isset($_GET['uploaded']) || !isset($_GET['left'])) {
show_error('Invalid information received from BitTorrent client');
}
$port = isset($_GET['port']) ? 0 + (int)$_GET['port'] : 0;
$ip = getip();
// IP Banned ??
$nip = ip2long($ip);
$res = mysqli_query($GLOBALS['conn'], "SELECT * FROM {$TABLE_PREFIX}bannedip WHERE $nip >= first AND $nip <= last") or error_log(__FILE__.' - '.__LINE__);
if (mysqli_num_rows($res) > 0) {
show_error('You are not authorized to use this tracker ('.$SITENAME.') -- Your IP address ('.$ip.') is BANNED.');
die();
}
// end banned IP
// only for internal tracked torrent!
$res_tor = mysqli_query($GLOBALS['conn'], "SELECT UNIX_TIMESTAMP(data) as data, uploader FROM {$TABLE_PREFIX}files WHERE external='no' AND info_hash='".$info_hash."'");
if (mysqli_num_rows($res_tor) == 0) {
show_error('Torrent is not authorized for use on this tracker.');
}
$downloaded = (float) ($_GET['downloaded']);
$uploaded = (float) ($_GET['uploaded']);
$left = (float) ($_GET['left']);
// if private announce turned on
if ($PRIVATE_ANNOUNCE) {
$pid = addslashes(stripslashes($pid));
// if PID empty string or not send by client
if ($pid == '' || !$pid) {
show_error('Please redownload the torrent. PID system is active and pid was not found in the torrent');
}
}
// PID turned on
if ($PRIVATE_ANNOUNCE) {
$respid = mysqli_query($GLOBALS['conn'], "SELECT u.*, level, can_download, WT FROM {$TABLE_PREFIX}users u INNER JOIN {$TABLE_PREFIX}users_level ul on u.id_level=ul.id WHERE pid='".$pid."' LIMIT 1");
if (!$respid || mysqli_num_rows($respid) != 1) {
show_error("Invalid PID (private announce): $pid. Please redownload torrent from $BASEURL.");
} else {
$rowpid = mysqli_fetch_assoc($respid);
if ($rowpid['can_download'] != 'yes' && $PRIVATE_ANNOUNCE) {
show_error("Sorry your level ($rowpid[level]) is not allowed to download from $BASEURL.");
} //waittime
elseif ($rowpid['WT'] > 0) {
$wait = 0;
if (((int) $rowpid['downloaded']) > 0) {
$ratio = number_format($rowpid['uploaded'] / $rowpid['downloaded'], 2);
} else {
$ratio = 0.0;
}
$added = mysqli_fetch_assoc($res_tor);
$vz = $added['data'];
$timer = floor((time() - $vz) / 3600);
if ($ratio < 1.0 && $rowpid['id'] != $added['uploader']) {
$wait = $rowpid['WT'];
}
$wait -= $timer;
if ($wait <= 0) {
$wait = 0;
} elseif ($wait != 0 && $left != 0) {
show_error($rowpid['username'].' your Waiting Time = '.$wait.' h');
}
}
//end
}
} else {
// PID turned off
$respid = mysqli_query($GLOBALS['conn'], "SELECT u.*, level, can_download, WT FROM {$TABLE_PREFIX}users u INNER JOIN {$TABLE_PREFIX}users_level ul on u.id_level=ul.id WHERE u.cip='$ip' LIMIT 1");
if (!$respid || mysqli_num_rows($respid) != 1) {
// maybe it's guest with new query I must found at least guest user
$respid = mysqli_query($GLOBALS['conn'], "SELECT u.*, level, can_download, WT FROM {$TABLE_PREFIX}users u INNER JOIN {$TABLE_PREFIX}users_level ul on u.id_level=ul.id WHERE u.id=1 LIMIT 1");
}
if (!$respid || mysqli_num_rows($respid) != 1) {
// do nothing but tracker is misconfigured!!!
// guest user not found...
} else {
$rowpid = mysqli_fetch_assoc($respid);
if ($rowpid['can_download'] != 'yes') {
show_error("Sorry your level ($rowpid[level]) is not allowed to download from $BASEURL.");
} //waittime
elseif ($rowpid['WT'] > 0) {
$wait = 0;
if (((int) $rowpid['downloaded']) > 0) {
$ratio = number_format($rowpid['uploaded'] / $rowpid['downloaded'], 2);
} else {
$ratio = 0.0;
}
$added = mysqli_fetch_assoc($res_tor);
$vz = $added['data'];
$timer = floor((time() - $vz) / 3600);
if ($ratio < 1.0 && $rowpid['id'] != $added['uploader']) {
$wait = $rowpid['WT'];
}
$wait -= $timer;
if ($wait <= 0) {
$wait = 0;
} elseif ($wait != 0 && $left != 0) {
show_error($rowpid['username'].' your Waiting Time = '.$wait.' h');
}
}
//end
}
}
if (isset($_GET['event'])) {
$event = $_GET['event'];
} else {
$event = '';
}
if (!isset($GLOBALS['ip_override'])) {
$GLOBALS['ip_override'] = true;
}
if (isset($_GET['numwant'])) {
if ($_GET['numwant'] < $GLOBALS['maxpeers'] && $_GET['numwant'] >= 0) {
$GLOBALS['maxpeers'] = $_GET['numwant'];
}
}
if (isset($_GET['trackerid'])) {
if (is_numeric($_GET['trackerid'])) {
$GLOBALS['trackerid'] = mysqli_real_escape_string($GLOBALS['conn'], $_GET['trackerid']);
}
}
if (!is_numeric($port) || !is_numeric($downloaded) || !is_numeric($uploaded) || !is_numeric($left)) {
show_error('Invalid numerical field(s) from client');
}
/////////////////////////////////////////////////////
// Checks
// Upgrade holdover: check for unset directives
if (!isset($GLOBALS['countbytes'])) {
$GLOBALS['countbytes'] = true;
}
/* Returns true if the user is firewalled, NAT'd, or whatever.
* The original tracker had its --nat_check parameter, so
* here is my version.
*/
function isFireWalled($hash, $peerid, $ip, $port)
{
// NAT checking off?
if (!$GLOBALS['NAT']) {
return false;
}
$protocol_name = 'BitTorrent protocol';
$theError = '';
// Hoping 10 seconds will be enough
$fd = fsockopen($ip, $port, $errno, $theError, 10);
if (!$fd) {
return true;
}
fclose($fd);
return false;
}
// Returns info on one peer
function getPeerInfo($user, $hash)
{
global $TABLE_PREFIX;
// If "trackerid" is set, let's try that
if (isset($GLOBALS['trackerid'])) {
$query = "SELECT peer_id,bytes,ip,port,status,lastupdate,sequence FROM {$TABLE_PREFIX}peers WHERE sequence=\"".$GLOBALS['trackerid']."\" AND infohash=\"$hash\"";
$results = mysqli_query($GLOBALS['conn'], $query) or show_error('Tracker error: invalid torrent');
$data = mysqli_fetch_assoc($results);
if (!$data || $data['peer_id'] != $user) {
// Damn, but don't crash just yet.
$query = "SELECT peer_id,bytes,ip,port,status,lastupdate,sequence from {$TABLE_PREFIX}peers where peer_id=\"$user\" AND infohash=\"$hash\"";
$results = mysqli_query($GLOBALS['conn'], $query) or show_error('Tracker error: invalid torrent');
$data = mysqli_fetch_assoc($results);
}
} else {
$query = "SELECT peer_id,bytes,ip,port,status,lastupdate,sequence from {$TABLE_PREFIX}peers where peer_id=\"$user\" AND infohash=\"$hash\"";
$results = mysqli_query($GLOBALS['conn'], $query) or show_error('Tracker error: invalid torrent');
$data = mysqli_fetch_assoc($results);
}
if (!($data)) {
return false;
}
$GLOBALS['trackerid'] = $data['sequence'];
return $data;
}
/////////////////////////////////////////////////////
// Any section of code might need to make a new peer, so this is a function here.
// I don't want to put it into funcsv2, even though it should, just for consistency's sake.
function start($info_hash, $ip, $port, $peer_id, $left, $downloaded = 0, $uploaded = 0, $upid = '')
{
global $BASEURL, $TABLE_PREFIX;
if (isset($_GET['ip']) && $GLOBALS['ip_override']) {
// compact check: valid IP address:
if ($_GET['ip'] !== long2ip(ip2long($_GET['ip']))) {
show_error('Invalid IP address. Must be standard dotted decimal (hostnames not allowed)');
}
$ip = mysqli_real_escape_string($GLOBALS['conn'], $_GET['ip']);
} else {
$ip = getip();
}
$ip = mysqli_real_escape_string($GLOBALS['conn'], $ip);
$agent = mysqli_real_escape_string($GLOBALS['conn'], $_SERVER['HTTP_USER_AGENT']);
$remotedns = gethostbyaddr($ip);
if ($_GET['ip']) {
$nuIP = $_GET['ip'];
} else {
$nuIP = '';
}
if ($remotedns === $nuIP) {
$remotedns = 'AA';
} else {
$remotedns = strtoupper($remotedns);
preg_match('/^(.+)\.([A-Z]{2,3})$/', $remotedns, $tldm);
if (!empty($tldm[2])) {
$remotedns = mysqli_real_escape_string($GLOBALS['conn'], $tldm[2]);
} else {
$remotedns = 'AA';
}
}
if ($left == 0) {
$status = 'seeder';
} else {
$status = 'leecher';
}
if (@isFireWalled($info_hash, $peer_id, $ip, $port)) {
$nat = 'Y';
} else {
$nat = 'N';
}
$compact = mysqli_real_escape_string($GLOBALS['conn'], str_pad(pack('Nn', ip2long($ip), $port), 6));
$peerid = mysqli_real_escape_string($GLOBALS['conn'], '2:ip'.strlen($ip).':'.$ip.'7:peer id20:'.hex2bin($peer_id)."4:porti{$port}e");
$no_peerid = mysqli_real_escape_string($GLOBALS['conn'], '2:ip'.strlen($ip).':'.$ip."4:porti{$port}e");
$results = @mysqli_query($GLOBALS['conn'], "INSERT INTO {$TABLE_PREFIX}peers SET infohash=\"$info_hash\", peer_id=\"$peer_id\", port=\"$port\", ip=\"$ip\", lastupdate=UNIX_TIMESTAMP(), bytes=\"$left\", status=\"$status\", natuser=\"$nat\", client=\"$agent\", dns=\"$remotedns\", downloaded=$downloaded, uploaded=$uploaded, pid=\"$upid\"");
// Special case: duplicated peer_id.
if (!$results) {
if (((is_object($GLOBALS['conn'])) ? mysqli_errno($GLOBALS['conn']) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)) == 1062) {
// Duplicate peer_id! Check IP address
$peer = getPeerInfo($peer_id, $info_hash);
if ($ip == $peer['ip']) {
// Same IP address. Tolerate this error.
return "WHERE natuser='N'";
}
// Different IP address. Assume they were disconnected, and alter the IP address.
quickQuery("UPDATE {$TABLE_PREFIX}peers SET ip=\"$ip\", compact=\"$compact\", with_peerid=\"$peerid\", without_peerid=\"$no_peerid\" WHERE peer_id=\"$peer_id\" AND infohash=\"$info_hash\"");
return "WHERE natuser='N'";
}
error_log('BtiTracker: start: '.((is_object($GLOBALS['conn'])) ? mysqli_error($GLOBALS['conn']) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
show_error('Tracker/database error. The details are in the error log.');
}
$GLOBALS['trackerid'] = ((is_null($___mysqli_res = mysqli_insert_id($GLOBALS['conn']))) ? false : $___mysqli_res);
@mysqli_query($GLOBALS['conn'], "UPDATE {$TABLE_PREFIX}peers SET sequence=\"".$GLOBALS['trackerid']."\", compact=\"$compact\", with_peerid=\"$peerid\", without_peerid=\"$no_peerid\" WHERE peer_id=\"$peer_id\" AND infohash=\"$info_hash\"");
if ($left == 0) {
summaryAdd('seeds', 1);
return "WHERE status=\"leecher\" AND natuser='N'";
} else {
summaryAdd('leechers', 1);
return "WHERE natuser='N'";
}
}
/// End of function start
// default for max peers with same pid/ip
if (!isset($GLOBALS['maxseeds'])) {
$GLOBALS['maxseeds'] = 2;
}
if (!isset($GLOBALS['maxleech'])) {
$GLOBALS['maxleech'] = 2;
}
// send random peers to client (direct print)
function sendRandomPeers($info_hash)
{
global $TABLE_PREFIX;
if ($GLOBALS['NAT']) {
$where = "WHERE infohash=\"$info_hash\" AND natuser = 'N'";
} else {
$where = "WHERE infohash=\"$info_hash\"";
}
$query = 'SELECT '.((isset($_GET['no_peer_id']) && $_GET['no_peer_id'] == 1) ? '' : 'peer_id,')."ip, port FROM {$TABLE_PREFIX}peers ".$where.' ORDER BY RAND() LIMIT '.$GLOBALS['maxpeers'];
echo 'd';
echo '8:intervali'.$GLOBALS['report_interval'].'e';
if (isset($GLOBALS['min_interval'])) {
echo '12:min intervali'.$GLOBALS['min_interval'].'e';
}
echo '5:peers';
$result = @mysqli_query($GLOBALS['conn'], $query);
if (isset($_GET['compact']) && $_GET['compact'] == '1') {
$p = '';
while ($row = mysqli_fetch_assoc($result)) {
$p .= str_pad(pack('Nn', ip2long($row['ip']), $row['port']), 6);
}
echo strlen($p).':'.$p;
} else { // no_peer_id or no feature supported
echo 'l';
while ($row = mysqli_fetch_assoc($result)) {
echo 'd2:ip'.strlen($row['ip']).':'.$row['ip'];
if (isset($row['peer_id'])) {
echo '7:peer id20:'.hex2bin($row['peer_id']);
}
echo '4:porti'.$row['port'].'ee';
}
echo 'e';
}
if (isset($GLOBALS['trackerid'])) {
echo '10:tracker id'.strlen($GLOBALS['trackerid']).':'.$GLOBALS['trackerid'];
}
echo 'e';
((mysqli_free_result($result) || (is_object($result) && (get_class($result) == 'mysqli_result'))) ? true : false);
}
// Deletes a peer from the system and performs all cleaning up
//
// $assumepeer contains the result of getPeerInfo, or false
// if we should grab it ourselves.
function killPeer($userid, $hash, $left, $assumepeer = false)
{
global $TABLE_PREFIX;
if (!$assumepeer) {
$peer = getPeerInfo($userid, $hash);
if (!$peer) {
return;
}
if ($left != $peer['bytes']) {
$bytes = bcsub($peer['bytes'], $left);
} else {
$bytes = 0;
}
} else {
$bytes = 0;
$peer = $assumepeer;
}
quickQuery("DELETE FROM {$TABLE_PREFIX}peers WHERE peer_id=\"$userid\" AND infohash=\"$hash\"");
if (mysqli_affected_rows($GLOBALS['conn']) == 1) {
if ($peer['status'] == 'leecher') {
summaryAdd('leechers', -1);
} else {
summaryAdd('seeds', -1);
}
if ($GLOBALS['countbytes'] && ((float) $bytes) > 0) {
summaryAdd('dlbytes', $bytes);
}
if ($peer['bytes'] != 0 && $left == 0) {
summaryAdd('finished', 1);
}
summaryAdd('lastcycle', 'UNIX_TIMESTAMP()', true);
}
}
// Transfers bytes from "left" to "dlbytes" when a peer reports in.
function collectBytes($peer, $hash, $left, $downloaded = 0, $uploaded = 0, $pid = '')
{
global $TABLE_PREFIX;
$peerid = $peer['peer_id'];
if (!$GLOBALS['countbytes']) {
quickQuery("UPDATE {$TABLE_PREFIX}peers SET lastupdate=UNIX_TIMESTAMP(), downloaded=$downloaded, uploaded=$uploaded, pid=\"$pid\" where infohash=\"$hash\" AND ".(isset($GLOBALS['trackerid']) ? "sequence=\"${GLOBALS['trackerid']}\"" : "peer_id=\"$peerid\""));
return;
}
$diff = bcsub($peer['bytes'], $left);
quickQuery("UPDATE {$TABLE_PREFIX}peers set ".(($diff != 0) ? "bytes=\"$left\"," : '')." lastupdate=UNIX_TIMESTAMP(), downloaded=$downloaded, uploaded=$uploaded, pid=\"$pid\" where infohash=\"$hash\" AND ".(isset($GLOBALS['trackerid']) ? 'sequence="'.$GLOBALS['trackerid'].'"' : "peer_id=\"$peerid\""));
// Anti-negative clause
if (((float) $diff) > 0) {
summaryAdd('dlbytes', $diff);
}
}
function runSpeed($info_hash, $delta)
{
global $TABLE_PREFIX;
//stick in our latest data before we calc it out
quickQuery("INSERT IGNORE INTO {$TABLE_PREFIX}timestamps (info_hash, bytes, delta, sequence) SELECT '$info_hash' AS info_hash, dlbytes, UNIX_TIMESTAMP() - lastSpeedCycle, NULL FROM {$TABLE_PREFIX}files WHERE info_hash=\"$info_hash\"");
// mysql blows sometimes so we have to read the data into php before updating it
$results = mysqli_query($GLOBALS['conn'], 'SELECT (MAX(bytes)-MIN(bytes))/SUM(delta), COUNT(*), MIN(sequence) FROM '.$TABLE_PREFIX.'timestamps WHERE info_hash="'.$info_hash.'"');
$data = mysqli_fetch_row($results);
summaryAdd('speed', $data[0], true);
summaryAdd('lastSpeedCycle', 'UNIX_TIMESTAMP()', true);
// if we have more than 20 drop the rest
if ($data[1] == 21) {
quickQuery("DELETE FROM {$TABLE_PREFIX}timestamps WHERE info_hash=\"$info_hash\" AND sequence=${data[2]}");
} elseif ($data[1] > 21) {
// This query requires MySQL 4.0.x, but should rarely be used.
quickQuery('DELETE FROM '.$TABLE_PREFIX.'timestamps WHERE info_hash="'.$info_hash.'" ORDER BY sequence LIMIT '.($data['1'] - 20));
}
}
//
// select how many users with same pid or ip
$results = mysqli_query($GLOBALS['conn'], "SELECT status, count(status) FROM {$TABLE_PREFIX}peers WHERE ".($PRIVATE_ANNOUNCE ? "pid=\"$pid\"" : "ip=\"$ip\"")." AND infohash=\"$info_hash\" AND peer_id<>\"$peer_id\" GROUP BY status") or show_error('Tracker error: invalid torrent');
$status = [];
while ($resstat = mysqli_fetch_row($results)) {
$status[$resstat[0]] = $resstat[1];
}
if (!isset($status['leecher'])) {
$status['leecher'] = 0;
}
if (!isset($status['seeder'])) {
$status['seeder'] = 0;
}
if ($status['seeder'] >= $GLOBALS['maxseeds'] || $status['leecher'] >= $GLOBALS['maxleech']) {
show_error("Sorry max peers reached! Redownload torrent from $BASEURL");
}
// end select
unset($status);
((mysqli_free_result($results) || (is_object($results) && (get_class($results) == 'mysqli_result'))) ? true : false);
// UPDATE users ratio down/up for every event on every announce
// only with the difference between stored down/up and sended by client
if ($LIVESTATS) {
$resstat = mysqli_query($GLOBALS['conn'], "SELECT `uploaded`, `downloaded` FROM `{$TABLE_PREFIX}peers` WHERE ".(($PRIVATE_ANNOUNCE) ? "`pid`='".$pid."'" : "`ip`='".$ip."'")." AND `infohash`='".$info_hash."' AND `peer_id`='".$peer_id."'");
if ($resstat && mysqli_num_rows($resstat) > 0) {
$livestat = mysqli_fetch_assoc($resstat);
// only if uploaded/downloaded are >= stored data in peer list
//if ($uploaded>=$livestat["uploaded"])
$newup = max(0, ($uploaded - $livestat['uploaded']));
//else
// $newup=$uploaded;
//if ($downloaded>=$livestat["downloaded"])
$newdown = max(0, ($downloaded - $livestat['downloaded']));
//else
// $newdown=$downloaded;
// rev 485
quickquery("UPDATE {$TABLE_PREFIX}users SET downloaded=IFNULL(downloaded,0)+$newdown, uploaded=IFNULL(uploaded,0)+$newup WHERE ".($PRIVATE_ANNOUNCE ? "pid='$pid'" : "cip='$ip'").'');
}
((mysqli_free_result($resstat) || (is_object($resstat) && (get_class($resstat) == 'mysqli_result'))) ? true : false);
// begin history - also this is registered live or not
if ($LOG_HISTORY) {
$resu = mysqli_query($GLOBALS['conn'], "SELECT id FROM {$TABLE_PREFIX}users WHERE ".($PRIVATE_ANNOUNCE ? "pid='$pid'" : "cip='$ip'").' ORDER BY lastconnect DESC LIMIT 1');
// if found at least one user should be 1
if ($resu && mysqli_num_rows($resu) == 1) {
$curuid = mysqli_fetch_assoc($resu);
quickQuery("UPDATE {$TABLE_PREFIX}history set uploaded=IFNULL(uploaded,0)+$newup, downloaded=IFNULL(downloaded,0)+$newdown WHERE uid=".$curuid['id']." AND infohash='$info_hash'");
}
((mysqli_free_result($resu) || (is_object($resu) && (get_class($resu) == 'mysqli_result'))) ? true : false);
}
// end history }
}
switch ($event) {
// client sent start
case 'started':
$start = start($info_hash, $ip, $port, $peer_id, $left, $downloaded, $uploaded, $pid);
sendRandomPeers($info_hash);
// begin history
if ($LOG_HISTORY) {
$resu = mysqli_query($GLOBALS['conn'], "SELECT id FROM {$TABLE_PREFIX}users WHERE ".($PRIVATE_ANNOUNCE ? "pid='$pid'" : "cip='$ip'").' ORDER BY lastconnect DESC LIMIT 1');
// if found at least one user should be 1
if ($resu && mysqli_num_rows($resu) == 1) {
$curuid = mysqli_fetch_assoc($resu);
quickQuery("UPDATE {$TABLE_PREFIX}history set active='yes',agent='".getagent($agent, $peer_id)."' WHERE uid=".$curuid['id']." AND infohash='$info_hash'");
// record is not present, create it (only if not seeder: original seeder don't exist in history table, other already exists)
if (mysqli_affected_rows($GLOBALS['conn']) == 0 && $left > 0) {
quickQuery("INSERT INTO {$TABLE_PREFIX}history (uid,infohash,active,agent) VALUES (".$curuid['id'].",'$info_hash','yes','".getagent($agent, $peer_id)."')");
}
}
((mysqli_free_result($resu) || (is_object($resu) && (get_class($resu) == 'mysqli_result'))) ? true : false);
}
// end history
break;
// client sent stop
case 'stopped':
killPeer($peer_id, $info_hash, $left);
sendRandomPeers($info_hash);
// update user uploaded/downloaded
if (!$LIVESTATS) {
@mysqli_query($GLOBALS['conn'], "UPDATE {$TABLE_PREFIX}users SET uploaded=IFNULL(uploaded,0)+$uploaded, downloaded=IFNULL(downloaded,0)+$downloaded WHERE ".($PRIVATE_ANNOUNCE ? "pid='$pid'" : "cip='$ip'").' AND id>1 LIMIT 1');
}
// begin history - if LIVESTAT, only the active/agent part
if ($LOG_HISTORY) {
$resu = mysqli_query($GLOBALS['conn'], "SELECT id FROM {$TABLE_PREFIX}users WHERE ".($PRIVATE_ANNOUNCE ? "pid='$pid'" : "cip='$ip'").' ORDER BY lastconnect DESC LIMIT 1');
// if found at least one user should be 1
if ($resu && mysqli_num_rows($resu) == 1) {
$curuid = mysqli_fetch_assoc($resu);
quickQuery("UPDATE {$TABLE_PREFIX}history set active='no',".($LIVESTATS ? '' : " uploaded=IFNULL(uploaded,0)+$uploaded, downloaded=IFNULL(downloaded,0)+$downloaded,")." agent='".getagent($agent, $peer_id)."' WHERE uid=".$curuid['id']." AND infohash='$info_hash'");
}
((mysqli_free_result($resu) || (is_object($resu) && (get_class($resu) == 'mysqli_result'))) ? true : false);
}
// end history }
break;
// client sent complete
case 'completed':
$peer_exists = getPeerInfo($peer_id, $info_hash);
if (!is_array($peer_exists)) {
start($info_hash, $ip, $port, $peer_id, $left, $downloaded, $uploaded, $pid);
} else {
quickQuery("UPDATE {$TABLE_PREFIX}peers SET bytes=0, status=\"seeder\", lastupdate=UNIX_TIMESTAMP(), downloaded=$downloaded, uploaded=$uploaded, pid=\"$pid\" WHERE sequence=\"".$GLOBALS['trackerid']."\" AND infohash=\"$info_hash\"");
// Race check
if (mysqli_affected_rows($GLOBALS['conn']) == 1) {
summaryAdd('leechers', -1);
summaryAdd('seeds', 1);
summaryAdd('finished', 1);
summaryAdd('lastcycle', 'UNIX_TIMESTAMP()', true);
} else {
collectBytes($peer_exists, $info_hash, $left, $downloaded, $uploaded, $pid);
}
}
sendRandomPeers($info_hash);
// begin history
if ($LOG_HISTORY) {
$resu = mysqli_query($GLOBALS['conn'], "SELECT id FROM {$TABLE_PREFIX}users WHERE ".($PRIVATE_ANNOUNCE ? "pid='$pid'" : "cip='$ip'").' ORDER BY lastconnect DESC LIMIT 1');
// if found at least one user should be 1
if ($resu && mysqli_num_rows($resu) == 1) {
$curuid = mysqli_fetch_assoc($resu);
// if user has already completed this torrent, mysql will give error because of unique index (uid+infohash)
// upload/download will be updated on stop event...
// record should already exist (created on stated event)
quickQuery("UPDATE {$TABLE_PREFIX}history SET date=UNIX_TIMESTAMP(),active='yes',agent='".getagent($agent, $peer_id)."' WHERE uid=".$curuid['id']." AND infohash='$info_hash'");
// record is not present, create it
if (mysqli_affected_rows($GLOBALS['conn']) == 0) {
quickQuery("INSERT INTO {$TABLE_PREFIX}history (uid,infohash,date,active,agent) VALUES (".$curuid['id'].",'$info_hash',UNIX_TIMESTAMP(),'yes','".getagent($agent, $peer_id)."')");
}
}
((mysqli_free_result($resu) || (is_object($resu) && (get_class($resu) === 'mysqli_result'))) ? true : false);
}
// end history
break;
// client sent no event
case '':
$peer_exists = getPeerInfo($peer_id, $info_hash);
$where = "WHERE natuser='N'";
if (!is_array($peer_exists)) {
$where = start($info_hash, $ip, $port, $peer_id, $left, $downloaded, $uploaded, $pid);
}
if ($peer_exists['bytes'] != 0 && $left == 0) {
quickQuery("UPDATE {$TABLE_PREFIX}peers SET bytes=0, status=\"seeder\", lastupdate=UNIX_TIMESTAMP(), downloaded=$downloaded, uploaded=$uploaded, pid=\"$pid\" WHERE sequence=\"".$GLOBALS['trackerid']."\" AND infohash=\"$info_hash\"");
if (mysqli_affected_rows($GLOBALS['conn']) == 1) {
summaryAdd('leechers', -1);
summaryAdd('seeds', 1);
summaryAdd('finished', 1);
summaryAdd('lastcycle', 'UNIX_TIMESTAMP()', true);
} else {
collectBytes($peer_exists, $info_hash, $left, $downloaded, $uploaded, $pid);
}
} else {
collectBytes($peer_exists, $info_hash, $left, $downloaded, $uploaded, $pid);
}
sendRandomPeers($info_hash);
break;
// not valid event
default:
show_error('Invalid event from client.');
}
if ($GLOBALS['countbytes']) {
// Once every minute or so, we run the speed update checker.
$query = @mysqli_query($GLOBALS['conn'], "SELECT UNIX_TIMESTAMP() - lastSpeedCycle FROM {$TABLE_PREFIX}files WHERE info_hash=\"$info_hash\"");
$results = mysqli_fetch_row($query);
if ($results[0] >= 120) {
@runSpeed($info_hash, $results[0]);
}
}
// Finally, it's time to do stuff to the summary table.
if (!empty($summaryupdate)) {
$stuff = '';
foreach ($summaryupdate as $column => $value) {
$stuff .= ', '.$column.($value[1] ? '='.$value[0] : "=IF(($column<".abs($value[0]).' AND '.$value[0]."<0),0,$column+".$value[0].')');
}
mysqli_query($GLOBALS['conn'], "UPDATE {$TABLE_PREFIX}files SET ".substr($stuff, 1)." WHERE info_hash=\"$info_hash\"");
}
// generaly not needed, but
// just in case server don't close connection
((is_null($___mysqli_res = mysqli_close($GLOBALS['conn']))) ? false : $___mysqli_res);
?>