lib/Net/BitTorrent.pm

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