blib/lib/Net/BitTorrent.pm untested

filter: Statementstmt 0.0% 0 / 632 Branchbran 0.0% 0 / 322 Conditioncond 0.0% 0 / 151 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 35 Podpod n/a totaltotal 0.0% 0 / 1140 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 use v5.40;
2 use feature 'class', 'try';
3 no warnings 'experimental::class', 'experimental::builtin', 'experimental::try';
4 use Net::BitTorrent::Emitter;
5 #
6 class Net::BitTorrent v2.1.0 : isa(Net::BitTorrent::Emitter) {
7 use Net::BitTorrent::Torrent;
8 use Net::BitTorrent::DHT;
9 use Net::uTP::Manager; # Standalone spin-off
10 use Net::BitTorrent::Protocol::MSE;
11 use Digest::SHA qw[sha1];
12 use Crypt::URandom qw[urandom];
13 use version;
14 use Time::HiRes qw[time];
15 use Net::BitTorrent::Types qw[:encryption];
16 use Algorithm::RateLimiter::TokenBucket;
17 use Net::Multicast::PeerDiscovery;
18 use Net::BitTorrent::SSRF qw[is_safe_ip];
19 #
20 field %torrents; # infohash => Torrent object
21 field %pending_peers; # transport => Peer object
22 field $dht;
23 field $tcp_listener;
24 field $tick_debt = 0;
25 field $utp : reader = Net::uTP::Manager->new();
26 field $lpd;
27 field $node_id : reader : writer;
28 field %dht_queries; # tid => { cb => sub, type => ... }
29 field %dht_index; # infohash_hex => timestamp (BEP 51 crawling)
30 field $port_mapper : reader;
31 field $port : param : reader = 49152 + int( rand(10000) );
32 field $user_agent : param : reader //= join '/', __CLASS__, our $VERSION;
33 field $debug : param : reader //= 0;
34 field $encryption : param : reader = ENCRYPTION_REQUIRED;
35  
36 # Feature Toggles (Default to enabled)
37 field $bep05 : param = 1; # DHT
38 field $bep06 : param = 1; # Fast Extension
39 field $bep09 : param = 1; # Metadata Exchange
40 field $bep10 : param = 1; # Extension Protocol
41 field $bep11 : param = 1; # PEX
42 field $bep52 : param = 1; # v2
43 field $bep55 : param = 1; # Holepunching
44 field $limit_up : reader;
45 field $limit_down : reader;
46 field $upnp_enabled : param = 0;
47 field $max_peers : param : reader : writer = 500;
48 field %_ip_connections; # ip => count of active connections
49 field %_mse_probes; # ip => [ timestamps ] for MSE probe rate limiting
50 use constant MAX_PER_IP_CONNECTIONS => 50;
51 use constant MAX_MSE_PROBES_PER_IP => 5; # Max MSE handshake probes per IP in 60s
52 use constant MAX_CONNECT_ATTEMPTS_PER_MIN => 30; # Max outgoing connection attempts per IP per minute
53 use constant MAX_UDP_PACKETS_PER_TICK => 100; # Max UDP packets processed per tick (flood protection)
54  
55 method _count_active_peers () {
56 my $count = 0;
57 $count += keys %{ $_->peer_objects_hash } for values %torrents;
58 return $count;
59 }
60 method _at_global_peer_limit () { ( ( scalar keys %pending_peers ) + $self->_count_active_peers() ) >= $max_peers }
61 method _at_per_ip_limit ($ip) { ( $_ip_connections{$ip} // 0 ) >= MAX_PER_IP_CONNECTIONS }
62 #
63 method on_peer_disconnected ($ip) {
64 $ip // return;
65 $_ip_connections{$ip}-- if exists $_ip_connections{$ip} && $_ip_connections{$ip} > 0;
66 }
67  
68 # Verification Throttling
69 field @hashing_queue; # Array of { torrent => $t, index => $i, data => $d }
70 field $hashing_rate_limit : writer = 1024 * 1024 * 500; # 500MB/s limit for hashing
71 field $hashing_allowance = 0;
72 my $MAX_HASHING_QUEUE_SIZE = 32; # Max pieces waiting for verification (~8MB at 256KB/piece)
73  
74 method features () {
75 { bep05 => $bep05, bep06 => $bep06, bep09 => $bep09, bep10 => $bep10, bep11 => $bep11, bep52 => $bep52, bep55 => $bep55 };
76 }
77 ADJUST {
78 $node_id //= _generate_peer_id();
79  
80 # Normalize encryption param
81 if ( defined $encryption && $encryption !~ /^\d+$/ ) {
82 if ( $encryption eq 'none' ) { $encryption = ENCRYPTION_NONE }
83 elsif ( $encryption eq 'preferred' ) { $encryption = ENCRYPTION_PREFERRED }
84 elsif ( $encryption eq 'required' ) { $encryption = ENCRYPTION_REQUIRED }
85 }
86 my $weak_self = $self;
87 builtin::weaken($weak_self);
88  
89 # TCP Listener
90 use IO::Socket::IP;
91 $tcp_listener = IO::Socket::IP->new( LocalPort => $port, Listen => 128, ReuseAddr => 1, Blocking => 0 );
92 if ($tcp_listener) {
93 $self->_emit_log( 'debug', 'TCP listener started on port ' . $port ) if $debug;
94 }
95 else {
96 $self->_emit_log( 'error', "Could not start TCP listener on port $port: $!" );
97 }
98 $utp->on(
99 new_connection => sub ( $utp_conn, $ip, $port ) {
100 return unless $weak_self;
101 return if $weak_self->_at_global_peer_limit();
102 return if $weak_self->_at_per_ip_limit($ip);
103  
104 #~ warn " [uTP] Incoming connection from $ip:$port\n";
105 use Net::BitTorrent::Protocol::HandshakeOnly;
106 use Net::BitTorrent::Peer;
107 my $proto = Net::BitTorrent::Protocol::HandshakeOnly->new(
108 infohash => undef, # Dummy, will be overwritten by any incoming
109 peer_id => $weak_self->node_id, # Dummy
110 on_handshake_cb => sub ( $ih, $id ) {
111 $weak_self->_upgrade_pending_peer( $utp_conn, $ih, $id, $ip, $port );
112 }
113 );
114 my $peer = Net::BitTorrent::Peer->new(
115 protocol => $proto,
116 torrent => undef, # Not known yet
117 transport => $utp_conn,
118 ip => $ip,
119 port => $port,
120 debug => $debug
121 );
122 $pending_peers{$utp_conn} = $peer;
123 }
124 );
125 $limit_up = Algorithm::RateLimiter::TokenBucket->new( limit => 0 );
126 $limit_down = Algorithm::RateLimiter::TokenBucket->new( limit => 0 );
127  
128 # Initialize LPD (BEP 14)
129 $lpd = Net::Multicast::PeerDiscovery->new();
130 $lpd->on(
131 peer_found => sub ($p_info) {
132 return unless $weak_self;
133 if ( my $t = $torrents{ $p_info->{info_hash} } ) {
134 $t->add_peer( { ip => $p_info->{ip}, port => $p_info->{port} } );
135 }
136 }
137 );
138  
139 # Initialize PortMapper if enabled and available
140 if ($upnp_enabled) {
141 builtin::load_module 'Acme::UPnP';
142 my $mapper = Acme::UPnP->new();
143 if ( $mapper->is_available() ) {
144 $port_mapper = $mapper;
145 }
146 else {
147 #~ warn " [UPnP] UPnP requested but Net::UPnP::ControlPoint not available. Skipping.\n";
148 $upnp_enabled = 0; # Disable UPnP if module not available
149 $port_mapper = undef; # Explicitly set to undef
150 }
151 }
152 else {
153 $port_mapper = undef; # Ensure it's undef if UPnP is disabled
154 }
155  
156 # Register PortMapper events if port_mapper is initialized
157 if ($port_mapper) {
158  
159 #~ $port_mapper->on( 'device_found', sub ($name_hash) { warn " [UPnP] Device found: $name_hash->{name}\n"; } );
160 #~ $port_mapper->on( 'device_not_found', sub { warn " [UPnP] No device found.\n"; } );
161 #~ $port_mapper->on( 'map_success',
162 #~ sub ($args) { warn " [UPnP] Port mapped: $args->{ext_p}/$args->{proto} for $args->{int_p} ($args->{desc})\n"; } );
163 #~ $port_mapper->on( 'map_failed', sub ($args) { warn " [UPnP] Port map failed: $args->{err_c} - $args->{err_d}\n"; } );
164 #~ $port_mapper->on( 'unmap_success', sub ($args) { warn " [UPnP] Port unmapped: $args->{ext_p}/$args->{proto}\n"; } );
165 #~ $port_mapper->on( 'unmap_failed', sub ($args) { warn " [UPnP] Port unmap failed: $args->{err_c} - $args->{err_d}\n"; } );
166 $self->forward_ports();
167 }
168 }
169  
170 sub _generate_peer_id () {
171 my $v_id = '200'; # Hardcoded version for stability in ID generation
172 my $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
173 return pack( 'a20', sprintf( '-NB%sS-%sSanko', $v_id, join( '', map { substr( $chars, unpack( 'N', urandom(4) ) % 66, 1 ) } 1 .. 7 ) ) );
174  
175 #~ $self->_emit( log => ' [DEBUG] Generated Peer ID: ' . unpack( 'H*', $id ) . " (" . $id . ")\n", level => 'debug' ) if $self->debug;
176 }
177  
178 method forward_ports () {
179 if ($port_mapper) {
180 $port_mapper->discover_device();
181 }
182 }
183  
184 method shutdown () {
185 if ($port_mapper) {
186 $port_mapper->unmap_port( $port, 'TCP' );
187 $port_mapper->unmap_port( $port, 'UDP' );
188 }
189 for my $t ( values %torrents ) {
190 $t->stop if $t;
191 }
192 }
193  
194 method remove_torrent ($thing) {
195 my $removed;
196 if ( ref $thing && $thing->can('infohash_v1') ) {
197 my $ih1 = $thing->infohash_v1;
198 my $ih2 = $thing->infohash_v2;
199 $removed = delete $torrents{$ih1} if $ih1 && exists $torrents{$ih1};
200 delete $torrents{$ih2} if $ih2 && exists $torrents{$ih2};
201 if ( $removed && $removed != $thing ) {
202 $torrents{$ih1} = $removed if $ih1;
203 $torrents{$ih2} = $removed if $ih2;
204 $self->_emit_log( 'warn', 'remove_torrent: object does not match stored torrent' );
205 return undef;
206 }
207 }
208 elsif ( defined $thing && ( length($thing) == 40 || length($thing) == 64 ) && $thing =~ /^[0-9a-f]+$/i ) {
209 my $ih = pack( 'H*', $thing );
210 $removed = delete $torrents{$ih};
211 }
212 elsif ( defined $thing && ref $thing eq 'Net::BitTorrent::Torrent' ) {
213 for my $k ( keys %torrents ) {
214 if ( $torrents{$k} == $thing ) {
215 $removed = delete $torrents{$k};
216 last;
217 }
218 }
219 }
220 if ($removed) {
221 $removed->stop();
222 $self->_emit( 'torrent_removed', $removed );
223 return $removed;
224 }
225 $self->_emit_log( 'debug', 'remove_torrent: torrent not found' );
226 return undef;
227 }
228  
229 method handle_udp_packet ( $data, $addr ) {
230 return unless length $data;
231 my $first = substr( $data, 0, 1 );
232 if ( $first eq 'd' ) {
233  
234 # Likely DHT
235 return $self->dht->handle_incoming( $data, $addr ) if $self->dht;
236 }
237 elsif ( ord($first) >> 4 == 1 ) {
238  
239 # Likely uTP (version 1)
240 my $res = $utp->handle_packet( $data, $addr );
241 if ($res) {
242  
243 # Send response back
244 $self->dht->socket->send( $res, 0, $addr );
245 }
246 }
247 }
248  
249 method _handle_new_tcp_transport ($transport) {
250 my $weak_self = $self;
251 builtin::weaken($weak_self);
252 my $weak_transport = $transport;
253 builtin::weaken($weak_transport);
254  
255 # We wait for the first chunk of data to decide if it's PWP or MSE
256 $transport->on(
257 data => sub ( $emitter, $data ) {
258 return unless $weak_self && $weak_transport;
259 my $entry = $weak_self->pending_peers_hash->{$weak_transport};
260 return unless $entry;
261 if ( $entry->{peer} ) {
262 $entry->{peer}->on_data($data);
263 }
264 else {
265 $weak_self->_autodetect_protocol( $weak_transport, $data );
266 }
267 }
268 );
269  
270 # Store in pending_peers to keep it alive
271 $pending_peers{$transport} = { transport => $transport, timestamp => time() };
272 }
273  
274 method _autodetect_protocol ( $transport, $data ) {
275 my $entry = $pending_peers{$transport};
276 return unless $entry;
277 return if $entry->{detected};
278  
279 # If we already have a peer object or a filter, this data is for them.
280 if ( $entry->{peer} || $transport->filter ) {
281 return;
282 }
283 $entry->{detected} = 1;
284 my $first_byte = ord( substr( $data, 0, 1 ) );
285 if ( $first_byte == 0x13 ) {
286 if ( $encryption == ENCRYPTION_REQUIRED ) {
287 $self->_emit_log( 'debug', 'Rejecting plaintext connection because encryption is required' ) if $debug;
288 my $rip = $transport->socket->peerhost // '';
289 $_ip_connections{$rip}-- if $_ip_connections{$rip} && $_ip_connections{$rip} > 0;
290 $transport->socket->close();
291 delete $pending_peers{$transport};
292 return;
293 }
294 $self->_emit_log( 'debug', 'Autodetected PWP handshake' ) if $debug;
295 use Net::BitTorrent::Protocol::HandshakeOnly;
296 my $proto = Net::BitTorrent::Protocol::HandshakeOnly->new(
297 infohash => undef,
298 peer_id => $self->node_id,
299 on_handshake_cb => sub ( $ih, $id ) {
300 $self->_upgrade_pending_peer( $transport, $ih, $id, $transport->socket->peerhost, $transport->socket->peerport );
301 }
302 );
303 $entry->{peer} = Net::BitTorrent::Peer->new(
304 protocol => $proto,
305 transport => $transport,
306 torrent => undef,
307 ip => $transport->socket->peerhost,
308 port => $transport->socket->peerport,
309 debug => $debug
310 );
311  
312 # Feed the data we already read to the new protocol handler
313 $entry->{peer}->on_data($data);
314 }
315 else {
316 $self->_emit_log( 'debug', 'Autodetected potential MSE handshake' ) if $debug;
317  
318 # We need to wait until we have req #2, then XOR it with each infohash we have until one matches
319 $self->_handle_incoming_mse( $transport, $data );
320 }
321 }
322  
323 method _handle_incoming_mse ( $transport, $data ) {
324 my $rip = $transport->socket->peerhost // '' if $transport->socket;
325 if ($rip) { # Rate limit MSE handshake probes per IP
326 my $now = time;
327 $_mse_probes{$rip} //= [];
328 @{ $_mse_probes{$rip} } = grep { $_ > $now - 60 } @{ $_mse_probes{$rip} };
329 if ( scalar @{ $_mse_probes{$rip} } >= MAX_MSE_PROBES_PER_IP ) {
330 $self->_emit_log( 'debug', "MSE probe rate limit exceeded for $rip" ) if $debug;
331 $transport->close();
332 return;
333 }
334 push @{ $_mse_probes{$rip} }, $now;
335 }
336 my $weak_self = $self;
337 builtin::weaken($weak_self);
338 my $mse = Net::BitTorrent::Protocol::MSE->new(
339 infohash => undef, # Not known yet
340 is_initiator => 0,
341 on_infohash_probe => sub ( $mse_obj, $xor_part, $s ) {
342 return undef unless $weak_self;
343 my $torrents = $weak_self->torrents();
344 for my $t (@$torrents) {
345 my $ih1 = $t->infohash_v1;
346 my $ih2 = $t->infohash_v2;
347 for my $ih ( grep {defined} ( $ih1, $ih2 ) ) {
348 my $expected_xor = $mse_obj->_xor_strings( sha1( 'req2' . $ih ), sha1( 'req3' . $s ) );
349 if ( $xor_part eq $expected_xor ) {
350 $weak_self->_emit_log( 'debug', "MSE matched infohash: " . unpack( 'H*', $ih ) ) if $weak_self->debug;
351 return $ih;
352 }
353 }
354 }
355 return undef;
356 }
357 );
358 my $weak_transport = $transport;
359 builtin::weaken($weak_transport);
360 $mse->on(
361 'infohash_identified',
362 sub ( $emitter, $ih ) {
363 return unless $weak_self && $weak_transport;
364 $weak_self->_upgrade_pending_peer( $weak_transport, $ih, undef, $weak_transport->socket->peerhost,
365 $weak_transport->socket->peerport );
366 }
367 );
368 $transport->set_filter($mse);
369 $self->_emit_log( 'debug', "Incoming MSE handshake started" ) if $debug;
370  
371 # If MSE fails (bad crypto, no infohash match), close the pending connection immediately
372 $transport->on(
373 'filter_failed',
374 sub ( $emitter, $leftover ) {
375 return unless $weak_self;
376 $weak_self->_emit_log( 'debug', 'Incoming MSE handshake failed, closing connection' ) if $weak_self->debug;
377 my $entry = $weak_self->pending_peers_hash->{$transport};
378 if ($entry) {
379 if ( $transport->socket ) {
380 my $rip = $transport->socket->peerhost // '';
381 $weak_self->{_ip_connections}{$rip}-- if $weak_self->{_ip_connections}{$rip};
382 }
383 $transport->socket->close() if $transport->socket;
384 delete $weak_self->pending_peers_hash->{$transport};
385 }
386 }
387 );
388  
389 # Feed the data we already have
390 $mse->receive_data($data);
391 my $entry = $pending_peers{$transport};
392 $entry->{mse} = $mse;
393 }
394  
395 method _upgrade_pending_peer ( $transport, $ih, $peer_id, $ip, $port ) {
396 my $entry = $pending_peers{$transport};
397 if ( !$entry ) {
398  
399 # Already upgraded or timed out
400 return;
401 }
402 delete $pending_peers{$transport};
403 my $torrent = $torrents{$ih};
404 if ( !$torrent ) {
405 $self->_emit_log( 'debug', "Handshake for unknown torrent " . unpack( 'H*', $ih ) . " from $ip:$port" ) if $debug;
406 if ( $transport->socket ) {
407 $_ip_connections{$ip}-- if $_ip_connections{$ip} && $_ip_connections{$ip} > 0;
408 $transport->socket->close();
409 }
410 return;
411 }
412 if ( keys %{ $torrent->peer_objects_hash } >= $torrent->max_peers ) {
413 $self->_emit_log( 'debug', "Per-torrent peer limit reached for " . unpack( 'H*', $ih ) . " from $ip:$port" ) if $debug;
414 if ( $transport->socket ) {
415 $_ip_connections{$ip}-- if $_ip_connections{$ip} && $_ip_connections{$ip} > 0;
416 $transport->socket->close();
417 }
418 return;
419 }
420 use Net::BitTorrent::Protocol::PeerHandler;
421 my $p_handler = Net::BitTorrent::Protocol::PeerHandler->new(
422 infohash => $ih,
423 peer_id => $self->node_id,
424 features => $torrent->features,
425 debug => $debug,
426 metadata_size => $torrent->metadata ? length( Net::BitTorrent::Protocol::BEP03::Bencode::bencode( $torrent->metadata->{info} ) ) : 0
427 );
428 my $peer;
429 if ( $entry->{peer} ) {
430 $peer = $entry->{peer};
431 $peer->set_protocol($p_handler);
432 $peer->set_torrent($torrent);
433 }
434 else {
435 $peer = Net::BitTorrent::Peer->new(
436 protocol => $p_handler,
437 torrent => $torrent,
438 transport => $transport,
439 ip => $ip,
440 port => $port,
441 debug => $debug,
442 mse => $entry->{mse},
443 encryption => $encryption
444 );
445 }
446 $p_handler->set_peer($peer);
447 $p_handler->set_parent_emitter($peer);
448 if ( defined $peer_id ) {
449 $p_handler->on_handshake( $ih, $peer_id );
450 }
451 $torrent->register_peer_object($peer);
452 }
453 method set_limit_down ($val) { $limit_down->set_limit($val) }
454 method hashing_queue_size () { scalar @hashing_queue }
455  
456 method queue_verification ( $torrent, $index, $data ) {
457 if ( @hashing_queue >= $MAX_HASHING_QUEUE_SIZE ) {
458 $self->_emit_log( 'warn', "Hashing queue full ($MAX_HASHING_QUEUE_SIZE), draining to make room" );
459 while ( @hashing_queue && $hashing_allowance >= length( $hashing_queue[0]{data} ) ) {
460 my $task = shift @hashing_queue;
461 $hashing_allowance -= length( $task->{data} );
462 $task->{torrent}->_verify_queued_piece( $task->{index}, $task->{data} );
463 }
464 if ( @hashing_queue >= $MAX_HASHING_QUEUE_SIZE ) {
465 $self->_emit_log( 'warn', "Hashing queue still full after drain, dropping piece $index verification" );
466 return;
467 }
468 }
469 $self->_emit_log( 'info', "PIECE $index: Queuing for verification (" . length($data) . " bytes)" );
470 push @hashing_queue, { torrent => $torrent, index => $index, data => $data };
471 }
472  
473 method _process_hashing_queue ($delta) {
474 $hashing_allowance += $hashing_rate_limit * $delta;
475 if ( @hashing_queue && $hashing_allowance < length( $hashing_queue[0]{data} ) ) {
476 $self->_emit_log( 'info',
477 sprintf( 'Hashing Throttled: %.2f%% of next piece ready', ( $hashing_allowance / length( $hashing_queue[0]{data} ) ) * 100 ) );
478 }
479 while (@hashing_queue) {
480 my $task = $hashing_queue[0];
481 my $len = length( $task->{data} );
482 if ( $hashing_allowance >= $len ) {
483 shift @hashing_queue;
484 $hashing_allowance -= $len;
485 $self->_emit_log( 'info', "PIECE $task->{index}: Processing hash..." );
486 $task->{torrent}->_verify_queued_piece( $task->{index}, $task->{data} );
487 }
488 else {
489 # Not enough allowance to finish this piece yet
490 last;
491 }
492 }
493 }
494  
495 method dht_get ( $target, $cb ) {
496 return unless $self->dht;
497  
498 # First, iterative find_node to get close to target.
499 # Then call get_remote on closest nodes
500 # Simplified: trigger iterative lookup and register callback
501 $self->dht->find_node_remote( $target, $_->[0], $_->[1] ) for @{ $self->dht->boot_nodes };
502 $dht_queries{$target} = { cb => $cb, type => 'get' };
503 }
504  
505 method dht_put ( $value, $cb = undef ) {
506 return unless $self->dht;
507 my $target = Digest::SHA::sha1($value);
508  
509 # Simplified: find nodes and then put
510 $self->dht->find_node_remote( $target, $_->[0], $_->[1] ) for @{ $self->dht->boot_nodes };
511 $dht_queries{$target} = { cb => $cb, type => 'put', value => $value };
512 }
513  
514 method dht_scrape ( $infohash, $cb ) {
515 return unless $self->dht;
516 $self->dht->scrape($infohash);
517 $dht_queries{$infohash} = { cb => $cb, type => 'scrape' };
518 }
519  
520 method dht_crawl () {
521 return unless $self->dht;
522  
523 # Random sample to discover new infohashes
524 my $random_target = urandom(20);
525 $self->dht->sample($random_target);
526 }
527 method dht_index () { return \%dht_index }
528  
529 method connect_to_peer ( $ip, $port, $ih ) {
530 return if $self->_at_global_peer_limit();
531 return if $self->_at_per_ip_limit($ip);
532  
533 # SSRF validation for outgoing connections
534 unless ( is_safe_ip($ip) ) {
535 $self->_emit_log( 'debug', 'connect_to_peer blocked by SSRF policy: ' . $ip ) if $debug;
536 return;
537 }
538 use IO::Socket::IP;
539 my $socket = IO::Socket::IP->new( PeerHost => $ip, PeerPort => $port, Type => SOCK_STREAM, Blocking => 0, );
540 return unless $socket;
541 $_ip_connections{$ip}++;
542 $self->_emit_log( 'debug', "Connecting to $ip:$port for " . unpack( 'H*', $ih ) ) if $debug;
543 use Net::BitTorrent::Transport::TCP;
544 my $transport = Net::BitTorrent::Transport::TCP->new( socket => $socket, connecting => 1 );
545  
546 # Add to pending_peers immediately
547 $pending_peers{$transport} = { transport => $transport, timestamp => time() };
548 my $weak_self = $self;
549 builtin::weaken($weak_self);
550 my $weak_transport = $transport;
551 builtin::weaken($weak_transport);
552 if ( $encryption == ENCRYPTION_REQUIRED || $encryption == ENCRYPTION_PREFERRED ) {
553 use Net::BitTorrent::Protocol::MSE;
554 my $mse = Net::BitTorrent::Protocol::MSE->new( infohash => $ih, is_initiator => 1, );
555 $mse->on(
556 'infohash_identified',
557 sub ( $emitter, $ih ) {
558 return unless $weak_self && $weak_transport;
559 $weak_self->_upgrade_pending_peer(
560 $weak_transport, $ih, undef,
561 $weak_transport->socket->peerhost,
562 $weak_transport->socket->peerport
563 );
564 }
565 );
566 $transport->set_filter($mse);
567 $pending_peers{$transport}{mse} = $mse;
568 $transport->on(
569 'filter_failed',
570 sub ( $emitter, $leftover ) {
571 return unless $weak_self && $weak_transport;
572 $weak_self->_emit_log( 'debug', "connect_to_peer: MSE failed, falling back to plaintext" ) if $weak_self->debug;
573 $weak_self->_upgrade_pending_peer(
574 $weak_transport, $ih, undef,
575 $weak_transport->socket->peerhost,
576 $weak_transport->socket->peerport
577 );
578 }
579 );
580 }
581 else {
582 # Plaintext outgoing: create peer immediately
583 $self->_upgrade_pending_peer( $transport, $ih, undef, $ip, $port );
584 }
585  
586 # Reuse incoming data handler logic
587 $transport->on(
588 'data',
589 sub ( $emitter, $data ) {
590 return unless $weak_self && $weak_transport;
591 my $entry = $weak_self->pending_peers_hash->{$weak_transport};
592 return unless $entry; # Might have been upgraded already
593 if ( $entry->{peer} ) {
594 $entry->{peer}->on_data($data);
595 }
596 else {
597 $weak_self->_autodetect_protocol( $weak_transport, $data );
598 }
599 }
600 );
601 return $transport;
602 }
603 method pending_peers_hash () { \%pending_peers }
604  
605 method add ( $thing, $base_path, %args ) {
606 if ( $thing =~ /^magnet:/i ) {
607 return $self->add_magnet( $thing, $base_path, %args );
608 }
609 elsif ( length($thing) == 20 || ( length($thing) == 40 && $thing =~ /^[0-9a-f]+$/i ) ) {
610 return $self->add_infohash( $thing, $base_path, %args );
611 }
612 elsif ( length($thing) == 32 || ( length($thing) == 64 && $thing =~ /^[0-9a-f]+$/i ) ) {
613 return $self->add_infohash( $thing, $base_path, %args );
614 }
615 elsif ( -f $thing ) {
616 return $self->add_torrent( $thing, $base_path, %args );
617 }
618 $self->_emit_log( 'error', "Don't know how to add '$thing'" );
619 return undef;
620 }
621  
622 method add_torrent ( $path, $base_path, %args ) {
623 my $t = Net::BitTorrent::Torrent->new( path => $path, base_path => $base_path, client => $self, debug => $debug, peer_id => $node_id, %args );
624 $torrents{ $t->infohash_v1 } = $t if $t->infohash_v1;
625 $torrents{ $t->infohash_v2 } = $t if $t->infohash_v2;
626 $self->_emit( 'torrent_added', $t );
627 return $t;
628 }
629  
630 method add_infohash ( $ih, $base_path, %args ) {
631 my $t
632 = Net::BitTorrent::Torrent->new( infohash => $ih, base_path => $base_path, client => $self, debug => $debug, peer_id => $node_id, %args );
633 $torrents{ $t->infohash_v1 } = $t if $t->infohash_v1;
634 $torrents{ $t->infohash_v2 } = $t if $t->infohash_v2;
635 $self->_emit( 'torrent_added', $t );
636 return $t;
637 }
638  
639 method add_magnet ( $uri, $base_path, %args ) {
640 use Net::BitTorrent::Protocol::BEP53;
641 my $m = Net::BitTorrent::Protocol::BEP53->parse($uri);
642 my $t = Net::BitTorrent::Torrent->new(
643 infohash_v1 => $m->infohash_v1,
644 infohash_v2 => $m->infohash_v2,
645 initial_trackers => $m->trackers,
646 initial_peers => $m->nodes, # x.pe
647 base_path => $base_path,
648 client => $self,
649 debug => $debug,
650 peer_id => $node_id,
651 %args
652 );
653 $torrents{ $t->infohash_v1 } = $t if $t->infohash_v1;
654 $torrents{ $t->infohash_v2 } = $t if $t->infohash_v2;
655 $self->_emit( 'torrent_added', $t );
656 return $t;
657 }
658  
659 method torrents () {
660 return [ values %torrents ];
661 }
662  
663 method dht () {
664 return undef unless $bep05;
665 if ( !$dht ) {
666 $dht = Net::BitTorrent::DHT->new(
667 node_id_bin => $node_id,
668 port => $port,
669 want_v6 => 1,
670 bep32 => 1,
671 bep42 => 0,
672 debug => $debug,
673 boot_nodes => [ [ 'router.bittorrent.com', 6881 ], [ 'router.utorrent.com', 6881 ], [ 'dht.transmissionbt.com', 6881 ] ]
674 );
675 my $weak_self = $self;
676 builtin::weaken($weak_self);
677 $dht->on(
678 'external_ip_detected',
679 sub ( $emitter, $ip ) {
680 return unless $weak_self;
681  
682 #~ warn " [DHT] External IP detected: $ip. Rotating node_id.\n";
683 # my $sec = Net::BitTorrent::DHT::Security->new();
684 # my $new_id = $sec->generate_node_id($ip);
685 # $weak_self->set_node_id($new_id);
686 # $dht->set_node_id($new_id);
687 }
688 );
689 $dht->bootstrap();
690 }
691 return $dht;
692 }
693  
694 method tick ( $timeout //= 0.1 ) {
695 $tick_debt += $timeout;
696 $tick_debt = 5.0 if $tick_debt > 5.0; # Max debt to avoid huge bursts
697 my $real_start = time();
698 while ( $tick_debt >= 0.01 ) {
699 my $slice = 0.1;
700 $slice = $tick_debt if $tick_debt < $slice;
701 $self->_run_one_tick($slice);
702 $tick_debt -= $slice;
703  
704 # Don't block the caller's main loop for more than 200ms
705 last if ( time() - $real_start ) > 0.2;
706 }
707 }
708  
709 method _run_one_tick ($timeout) {
710 $self->_emit_log( 'debug', "Net::BitTorrent::_run_one_tick starting (timeout=$timeout)" ) if $debug > 1;
711 my $start = time();
712 $limit_up->tick($timeout);
713 $limit_down->tick($timeout);
714  
715 # Accept incoming TCP connections
716 if ($tcp_listener) {
717 my $sel = IO::Select->new($tcp_listener);
718 if ( $sel->can_read(0) ) {
719 while ( my $socket = $tcp_listener->accept() ) {
720 if ( $self->_at_global_peer_limit() ) {
721 $socket->close();
722 next;
723 }
724 my $peer_ip = $socket->peerhost // '';
725 if ( $self->_at_per_ip_limit($peer_ip) ) {
726 $socket->close();
727 next;
728 }
729 $_ip_connections{$peer_ip}++;
730 $socket->blocking(0);
731 $self->_emit_log( 'debug', "Accepted TCP connection from " . $socket->peerhost . ":" . $socket->peerport ) if $debug;
732 use Net::BitTorrent::Transport::TCP;
733 my $transport = Net::BitTorrent::Transport::TCP->new( socket => $socket, connecting => 0 );
734  
735 # Autodetect MSE vs PWP will happen in the first data received
736 $self->_handle_new_tcp_transport($transport);
737 }
738 }
739 }
740 else {
741 $self->_emit_log( 'debug', "No TCP listener active" ) if $debug > 1;
742 }
743  
744 # Process hashing queue (throttled)
745 $self->_process_hashing_queue($timeout);
746  
747 # Update LPD
748 $lpd->tick($timeout) if $lpd;
749  
750 # Update torrents (including trackers and storage)
751 for my $ih ( keys %torrents ) {
752 $torrents{$ih}->tick($timeout);
753 }
754  
755 # Update pending peers (ones being autodetected or in handshake)
756 for my $t_key ( keys %pending_peers ) {
757 my $entry = $pending_peers{$t_key};
758 my $transport = $entry->{transport};
759 if ( $entry->{peer} ) {
760 $entry->{peer}->tick();
761 }
762 else {
763 # If no peer object yet, we still need to tick the transport
764 # to read the autodetection data.
765 $transport->tick();
766 }
767  
768 # Timeout old pending connections (30s)
769 if ( time() - $entry->{timestamp} > 30 ) {
770 if ($debug) {
771 my $host = 'unknown';
772 try {
773 if ( $transport->socket ) {
774 $host = $transport->socket->peerhost // 'unknown';
775 }
776 }
777 catch ($e) { }
778 $self->_emit_log( 'debug', "Timing out pending connection from $host" );
779 }
780 if ( $transport->socket ) {
781 my $rip = $transport->socket->peerhost // '';
782 $_ip_connections{$rip}-- if $_ip_connections{$rip} && $_ip_connections{$rip} > 0;
783 $transport->socket->close();
784 }
785 delete $pending_peers{$t_key};
786 }
787 }
788  
789 # Collect DHT events from direct packet processing
790 my ( @packet_nodes, @packet_peers, @packet_data );
791  
792 # Read from UDP socket (DHT/uTP)
793 if ( $dht && $dht->socket ) {
794 my $sel = IO::Select->new( $dht->socket );
795 my $udp_count = 0;
796 while ( $udp_count < MAX_UDP_PACKETS_PER_TICK && $sel->can_read(0) ) {
797 my $remote_addr = $dht->socket->recv( my $data, 65535 );
798 if ($remote_addr) {
799 my @res = $self->handle_udp_packet( $data, $remote_addr );
800 if (@res) {
801 push @packet_nodes, @{ $res[0] } if ref $res[0] eq 'ARRAY';
802 push @packet_peers, @{ $res[1] } if ref $res[1] eq 'ARRAY';
803 push @packet_data, $res[2] if $res[2];
804 }
805 $udp_count++;
806 }
807 }
808 }
809  
810 # Update uTP
811 my $utp_packets = $utp->tick($timeout);
812 for my $pkt (@$utp_packets) {
813  
814 # Send retransmissions etc.
815 # We use the DHT socket for convenience if it exists
816 if ( $dht && $dht->socket ) {
817  
818 # Need to convert ip/port to sockaddr
819 use Socket qw[pack_sockaddr_in inet_aton];
820 my $addr = pack_sockaddr_in( $pkt->{port}, inet_aton( $pkt->{ip} ) );
821 $dht->socket->send( $pkt->{data}, 0, $addr );
822 }
823 }
824  
825 # Update DHT
826 if ($dht) {
827 my ( $tick_nodes, $tick_peers, $tick_data ) = $dht->tick($timeout);
828 my @all_nodes = ( @{ $tick_nodes // [] }, @packet_nodes );
829 my @all_peers = ( @{ $tick_peers // [] }, @packet_peers );
830  
831 # Merge packet-derived data with tick-derived data
832 my @all_data = grep {defined} ( $tick_data, @packet_data );
833 if ( $debug && ( @all_nodes || @all_peers || @all_data ) ) {
834 $self->_emit_log( 'debug',
835 sprintf( "DHT tick+packets: nodes=%d, peers=%d, data=%d", scalar(@all_nodes), scalar(@all_peers), scalar(@all_data) ) );
836 }
837  
838 # If we found new nodes, add them to the frontier of starving torrents
839 if (@all_nodes) {
840 for my $t ( values %torrents ) {
841 next if scalar( @{ $t->peer_objects // [] } ) >= 20;
842 $t->add_dht_nodes( \@all_nodes );
843 }
844 }
845  
846 # Dispatch peers to relevant torrents
847 # Net::BitTorrent::DHT::handle_incoming returns (nodes, peers, data)
848 # The 'data' (result) hash contains 'queried_target' which is the infohash
849 # we were looking for when these peers were returned.
850 for my $d (@all_data) {
851 my $ih = $d->{queried_target};
852 if ( $ih && ( my $t = $torrents{$ih} ) ) {
853 if ( $debug && @all_peers ) {
854 $self->_emit_log( 'debug', "Dispatching " . scalar(@all_peers) . " peers to torrent " . unpack( "H*", $ih ) );
855 }
856 for my $peer (@all_peers) {
857 $t->add_peer($peer);
858 }
859 }
860 elsif ( $debug && $ih ) {
861 $self->_emit_log( 'debug', "DHT result for unknown infohash " . unpack( "H*", $ih ) );
862 }
863 }
864  
865 # Handle BEP 33, 44, 51 data
866 for my $d (@all_data) {
867 if ( exists $d->{samples} ) { # BEP 51
868 for my $ih ( @{ $d->{samples} } ) {
869 my $key = unpack( 'H*', $ih );
870 $dht_index{$key} = time();
871 if ( keys %dht_index > 1000 ) {
872  
873 # Remove oldest or just random?
874 # For simplicity, remove first key (random in Perl)
875 delete $dht_index{ ( keys %dht_index )[0] };
876 }
877 }
878 }
879 if ( exists $d->{v} ) { # BEP 44
880  
881 # Calculate target (immutable) or use key (mutable)
882 my $target = Digest::SHA::sha1( $d->{v} );
883 if ( my $q = delete $dht_queries{$target} ) {
884 $q->{cb}->( $d->{v}, $d ) if $q->{cb};
885 }
886 }
887 if ( exists $d->{sn} ) { # BEP 33
888  
889 # Scrape result - find matching torrent
890 if ( my $ih = $d->{queried_target} ) {
891 if ( my $t = $torrents{$ih} ) {
892 $t->handle_dht_scrape($d);
893 }
894 }
895 }
896 }
897 }
898  
899 # Update all torrents (evaluates choking, etc.)
900 for my $t ( values %torrents ) {
901 $t->tick($timeout);
902  
903 # BEP 14: Periodically announce on local network
904 # (Simplified: every ~60s if we tracked a timer, here we just do it occasionally)
905 if ( rand() < 0.01 ) { # Hack for now
906 if ($lpd) {
907 $lpd->announce( $t->infohash_v2, 6881 ) if $t->infohash_v2;
908 $lpd->announce( $t->infohash_v1, 6881 ) if $t->infohash_v1;
909 }
910 }
911 }
912 }
913  
914 method save_state ($path) {
915 use JSON::PP qw[encode_json];
916 use Path::Tiny qw[path];
917 my %data = ( node_id => $node_id, torrents => {}, );
918 my %seen;
919 for my $ih ( keys %torrents ) {
920 my $t = $torrents{$ih};
921 next if $seen{ builtin::refaddr($t) }++;
922 $data{torrents}{ unpack( 'H*', $ih ) } = $t->dump_state();
923 }
924  
925 # Add integrity checksum to detect tampering
926 my $payload = encode_json( \%data );
927 $data{_checksum} = unpack( 'H*', sha1($payload) );
928 path($path)->spew_utf8( encode_json( \%data ) );
929 }
930  
931 method load_state ($path) {
932 use JSON::PP qw[decode_json];
933 use Path::Tiny qw[path];
934 return unless path($path)->exists;
935 my $raw = path($path)->slurp_utf8;
936 my $data;
937 try { $data = decode_json($raw) }
938 catch ($e) {
939 $self->_emit_log( 'error', "Failed to parse state file: $e" );
940 return;
941 }
942 return unless ref $data eq 'HASH';
943  
944 # Verify integrity checksum
945 if ( defined $data->{_checksum} ) {
946 my $stored = delete $data->{_checksum};
947 my $expected = unpack( 'H*', sha1( encode_json($data) ) );
948 if ( $expected ne $stored ) {
949 $self->_emit_log( 'warn', 'State file integrity check failed, keeping current state' );
950 return;
951 }
952 }
953 if ( defined $data->{node_id} && length( $data->{node_id} ) == 20 ) {
954 $node_id = $data->{node_id};
955 }
956 else {
957 $self->_emit_log( 'warn', 'State file missing or invalid node_id, keeping current' );
958 }
959 if ( ref $data->{torrents} eq 'HASH' ) {
960 for my $ih_hex ( keys %{ $data->{torrents} } ) {
961 next unless $ih_hex =~ /^[0-9a-f]{40}$/i;
962 next unless ref $data->{torrents}{$ih_hex} eq 'HASH';
963 my $ih = pack( 'H*', $ih_hex );
964 if ( my $t = $torrents{$ih} ) {
965 $t->load_state( $data->{torrents}{$ih_hex} );
966 }
967 }
968 }
969 }
970  
971 method finished () {
972 return [ grep { $_->is_finished } values %torrents ];
973 }
974  
975 method wait ( $condition = undef, $timeout = undef ) {
976 my $start = time();
977 $condition //= sub {
978 my @t = values %torrents;
979 return 1 if !@t;
980 return ( grep { $_->is_finished } @t ) == @t;
981 };
982 while ( !$condition->($self) ) {
983 $self->tick(0.1);
984 if ( defined $timeout && ( time() - $start ) > $timeout ) {
985 return 0;
986 }
987 select( undef, undef, undef, 0.05 );
988 }
989 return 1;
990 }
991 };
992 #
993 1;