lib/Net/BitTorrent.pm

filter: Statementstmt 56.6% 361 / 637 Branchbran 30.2% 101 / 334 Conditioncond 19.6% 30 / 153 MC/DCmcdc 6.5% 6 / 92 Subroutinesub 70.9% 61 / 86 Podpod 67.8% 19 / 28 totaltotal 43.4% 578 / 1330 CC 247 SCAR 57.0
CC
247
Cov
44%
_run_one_tick
1100.6
remove_torrent
420.0
_upgrade_pending_peer
209.4
CRAP 299.4
« lib/Net/BitTorrent/DHT.pm ↑ Summary lib/Net/BitTorrent/Transport/TCP.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.1 : 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 :state];
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 2 ▶ 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 4 ▶ method on_peer_disconnected ($ip) {
Subroutine on_peer_disconnected: called CC=4 SCAR=16.9
Pod undocumented
64 4 ▶ $ip // return;
Condition50%1/2
$ip // (return)
l!l
40
MC/DC0%0/1
$ip // (return)
$ip
Truth table50%1/2
A
A= $ip
Aresult
11
00
65 4 ▶ $_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 4 4
Condition33%1/3
exists $_ip_connections{$ip} and $_ip_connections{$ip} > 0
!ll&&!rl&&r
400
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 108 ▶ 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 116 ▶ ADJUST {
Subroutine __ANON__: called CC=12 SCAR=28.1
78 116 ▶ $node_id //= _generate_peer_id();
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 116 ▶ 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 2 ▶ 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 1 ▶ 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 0 ▶ 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 33 ▶ method handle_udp_packet ( $data, $addr ) {
Subroutine handle_udp_packet: called CC=6 SCAR=25.9
Pod undocumented
230 33 ▶ return unless length $data;
Branch: 1 branch
BranchTrueFalseTotal
unless length $data 0 33 33
231 33 my $first = substr( $data, 0, 1 );
232 33 ▶ if ( $first eq 'd' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($first eq 'd') { } 33 0 33
elsif (ord($first) >> 4 == 1) { } 0 0 0
233  
234 # Likely DHT
235 33 ▶ return $self->dht->handle_incoming( $data, $addr ) if $self->dht;
Branch: 1 branch
BranchTrueFalseTotal
if $self->dht 33 0 33
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 0 ▶ 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(
257 0 ▶ data => sub ( $emitter, $data ) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
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 0 ▶ 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(
297 infohash => undef,
298 peer_id => $self->node_id,
299 0 ▶ on_handshake_cb => sub ( $ih, $id ) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 0 ▶ 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(
339 infohash => undef, # Not known yet
340 is_initiator => 0,
341 0 ▶ on_infohash_probe => sub ( $mse_obj, $xor_part, $s ) {
Subroutine __ANON__: not called CC=6 SCAR=37.4
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(
361 'infohash_identified',
362 0 ▶ sub ( $emitter, $ih ) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
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(
373 'filter_failed',
374 0 ▶ sub ( $emitter, $leftover ) {
Subroutine __ANON__: not called CC=8 SCAR=42.8
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 0 ▶ 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 83 ▶ method queue_verification ( $torrent, $index, $data ) {
Subroutine queue_verification: called CC=5 SCAR=18.0
Pod documented
457 83 ▶ if ( @hashing_queue >= $MAX_HASHING_QUEUE_SIZE ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@hashing_queue >= $MAX_HASHING_QUEUE_SIZE) 1 82 83
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 82 $self->_emit_log( 'info', "PIECE $index: Queuing for verification (" . length($data) . " bytes)" );
470 82 push @hashing_queue, { torrent => $torrent, index => $index, data => $data };
471 }
472  
473 59 ▶ method _process_hashing_queue ($delta) {
Subroutine _process_hashing_queue: called CC=5 SCAR=16.1
474 59 $hashing_allowance += $hashing_rate_limit * $delta;
475 59 ▶ 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"}) 1 58 59
Condition100%3/3
@hashing_queue and $hashing_allowance < length $hashing_queue[0]{"data"}
!ll&&!rl&&r
4991
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 1 sprintf( 'Hashing Throttled: %.2f%% of next piece ready', ( $hashing_allowance / length( $hashing_queue[0]{data} ) ) * 100 ) );
478 }
479 59 ▶ while (@hashing_queue) {
Branch: 1 branch
BranchTrueFalseTotal
if (@hashing_queue) 51 57 108
480 51 my $task = $hashing_queue[0];
481 51 my $len = length( $task->{data} );
482 51 ▶ if ( $hashing_allowance >= $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hashing_allowance >= $len) { } 49 2 51
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 2 last;
491 }
492 }
493 }
494  
495 0 ▶ 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 46 ▶ 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 0 ▶ 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 1 ▶ 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(
556 'infohash_identified',
557 0 ▶ sub ( $emitter, $ih ) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
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(
569 'filter_failed',
570 0 ▶ sub ( $emitter, $leftover ) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
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(
588 'data',
589 0 ▶ sub ( $emitter, $data ) {
Subroutine __ANON__: not called CC=5 SCAR=34.0
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 23 ▶ 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 71 ▶ 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 1 ▶ 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 12 ▶ 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 0 ▶ method torrents () { [ values %torrents ] }
Subroutine torrents: not called CC=1 SCAR=6.9
Pod documented
659 0 ▶ method torrents_hash () { \%torrents }
Subroutine torrents_hash: not called CC=1 SCAR=6.9
Pod documented
660  
661 279 ▶ method dht () {
Subroutine dht: called CC=3 SCAR=11.2
Pod undocumented
662 279 ▶ return undef unless $bep05;
Branch: 1 branch
BranchTrueFalseTotal
unless $bep05 7 272 279
663 272 ▶ if ( !$dht ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dht) 46 226 272
664 46 $dht = Net::BitTorrent::DHT->new(
665 node_id_bin => $node_id,
666 port => $port,
667 want_v6 => 1,
668 bep32 => 1,
669 bep42 => 0,
670 debug => $debug,
671 boot_nodes => [ [ 'router.bittorrent.com', 6881 ], [ 'router.utorrent.com', 6881 ], [ 'dht.transmissionbt.com', 6881 ] ]
672 );
673 46 my $weak_self = $self;
674 46 builtin::weaken($weak_self);
675 $dht->on(
676 'external_ip_detected',
677 0 ▶ sub ( $emitter, $ip ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
678 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
679  
680 #~ warn " [DHT] External IP detected: $ip. Rotating node_id.\n";
681 # my $sec = Net::BitTorrent::DHT::Security->new();
682 # my $new_id = $sec->generate_node_id($ip);
683 # $weak_self->set_node_id($new_id);
684 # $dht->set_node_id($new_id);
685 }
686 46 );
687 46 $dht->bootstrap();
688 }
689 272 return $dht;
690 }
691  
692 27 ▶ method tick ( $timeout //= 0.1 ) {
Subroutine tick: called CC=6 SCAR=18.2
Pod documented
693 27 $tick_debt += $timeout;
694 27 ▶ $tick_debt = 5.0 if $tick_debt > 5.0; # Max debt to avoid huge bursts
Branch: 1 branch
BranchTrueFalseTotal
if $tick_debt > 5 0 27 27
695 27 my $real_start = time();
696 27 ▶ while ( $tick_debt >= 0.01 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tick_debt >= "0.01") 54 0 54
697 54 my $slice = 0.025;
698 54 ▶ $slice = $tick_debt if $tick_debt < $slice;
Branch: 1 branch
BranchTrueFalseTotal
if $tick_debt < $slice 0 54 54
699 54 $self->_run_one_tick($slice);
700 54 $tick_debt -= $slice;
701  
702 # Don't block the caller's main loop for more than 50ms
703 54 ▶ last if ( time() - $real_start ) > 0.05;
Branch: 1 branch
BranchTrueFalseTotal
if &Net::BitTorrent::time() - $real_start > "0.05" 27 27 54
704 }
705 }
706  
707 54 ▶ method _run_one_tick ($timeout) {
Subroutine _run_one_tick: called CC=75 SCAR=70.0
708 54 ▶ $self->_emit_log( 'debug', "Net::BitTorrent::_run_one_tick starting (timeout=$timeout)" ) if $debug > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $debug > 1 0 54 54
709 54 my $start = time();
710 54 $limit_up->tick($timeout);
711 54 $limit_down->tick($timeout);
712  
713 # Accept incoming TCP connections
714 54 ▶ if ($tcp_listener) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tcp_listener) { } 54 0 54
715 54 my $sel = IO::Select->new($tcp_listener);
716 54 ▶ if ( $sel->can_read(0) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel->can_read(0)) 0 54 54
717 0 ▶ while ( my $socket = $tcp_listener->accept() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $socket = $tcp_listener->accept) 0 0 0
718 0 ▶ if ( $self->_at_global_peer_limit() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_at_global_peer_limit) 0 0 0
719 0 $socket->close();
720 0 next;
721 }
722 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
723 0 ▶ if ( $self->_at_per_ip_limit($peer_ip) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_at_per_ip_limit($peer_ip)) 0 0 0
724 0 $socket->close();
725 0 next;
726 }
727 0 $_ip_connections{$peer_ip}++;
728 0 $socket->blocking(0);
729 0 ▶ $self->_emit_log( 'debug', "Accepted TCP connection from " . $socket->peerhost . ":" . $socket->peerport ) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
730 25 ▶ use Net::BitTorrent::Transport::TCP;
Subroutine BEGIN: called CC=1 SCAR=0.0
731 0 my $transport = Net::BitTorrent::Transport::TCP->new( socket => $socket, connecting => 0 );
732  
733 # Autodetect MSE vs PWP will happen in the first data received
734 0 $self->_handle_new_tcp_transport($transport);
735 }
736 }
737 }
738 else {
739 0 ▶ $self->_emit_log( 'debug', "No TCP listener active" ) if $debug > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $debug > 1 0 0 0
740 }
741  
742 # Process hashing queue (throttled)
743 54 $self->_process_hashing_queue($timeout);
744  
745 # Update LPD
746 54 ▶ $lpd->tick($timeout) if $lpd;
Branch: 1 branch
BranchTrueFalseTotal
if $lpd 54 0 54
747  
748 # Update torrents (including trackers and storage)
749 54 for my $ih ( keys %torrents ) {
750 64 $torrents{$ih}->tick($timeout);
751 }
752  
753 # Update pending peers (ones being autodetected or in handshake)
754 54 for my $t_key ( keys %pending_peers ) {
755 0 my $entry = $pending_peers{$t_key};
756 0 my $transport = $entry->{transport};
757 0 ▶ if ( $entry->{peer} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{'peer'}) { } 0 0 0
758 0 $entry->{peer}->tick();
759 }
760 else {
761 # If no peer object yet, we still need to tick the transport
762 # to read the autodetection data.
763 0 $transport->tick();
764 }
765  
766 # Timeout old pending connections (30s)
767 0 ▶ if ( time() - $entry->{timestamp} > 30 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Net::BitTorrent::time() - $entry->{"timestamp"} > 30) 0 0 0
768 0 ▶ if ($debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 0 0
769 0 my $host = 'unknown';
770 0 try {
771 0 ▶ if ( $transport->socket ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($transport->socket) 0 0 0
772 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
773 }
774 }
775 catch ($e) { }
776 0 $self->_emit_log( 'debug', "Timing out pending connection from $host" );
777 }
778 0 ▶ if ( $transport->socket ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($transport->socket) 0 0 0
779 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
780 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
781 0 $transport->socket->close();
782 }
783 0 delete $pending_peers{$t_key};
784 }
785 }
786  
787 # Collect DHT events from direct packet processing
788 54 my ( @packet_nodes, @packet_peers, @packet_data );
789  
790 # Read from UDP socket (DHT/uTP)
791 54 ▶ if ( $dht && $dht->socket ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dht and $dht->socket) 12 42 54
Condition66%2/3
$dht and $dht->socket
!ll&&!rl&&r
42012
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
792 12 my $sel = IO::Select->new( $dht->socket );
793 12 my $udp_count = 0;
794 12 ▶ 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)) 33 12 45
Condition66%2/3
$udp_count < 100 and $sel->can_read(0)
!ll&&!rl&&r
01233
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
795 33 my $remote_addr = $dht->socket->recv( my $data, 65535 );
796 33 ▶ if ($remote_addr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remote_addr) 33 0 33
797 33 my @res = $self->handle_udp_packet( $data, $remote_addr );
798 33 ▶ if (@res) {
Branch: 1 branch
BranchTrueFalseTotal
if (@res) 33 0 33
799 33 ▶ push @packet_nodes, @{ $res[0] } if ref $res[0] eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $res[0] eq "ARRAY" 33 0 33
800 33 ▶ push @packet_peers, @{ $res[1] } if ref $res[1] eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $res[1] eq "ARRAY" 33 0 33
801 33 ▶ push @packet_data, $res[2] if $res[2];
Branch: 1 branch
BranchTrueFalseTotal
if $res[2] 1 32 33
802 }
803 33 $udp_count++;
804 }
805 }
806 }
807  
808 # Update uTP
809 54 my $utp_packets = $utp->tick($timeout);
810 54 for my $pkt (@$utp_packets) {
811  
812 # Send retransmissions etc.
813 # We use the DHT socket for convenience if it exists
814 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
815  
816 # Need to convert ip/port to sockaddr
817 25 ▶ use Socket qw[pack_sockaddr_in inet_aton];
Subroutine BEGIN: called CC=1 SCAR=0.0
818 0 my $addr = pack_sockaddr_in( $pkt->{port}, inet_aton( $pkt->{ip} ) );
819 0 $dht->socket->send( $pkt->{data}, 0, $addr );
820 }
821 }
822  
823 # Update DHT
824 54 ▶ if ($dht) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dht) 12 42 54
825 12 my ( $tick_nodes, $tick_peers, $tick_data ) = $dht->tick($timeout);
826 12 ▶ my @all_nodes = ( @{ $tick_nodes // [] }, @packet_nodes );
Condition50%1/2
$tick_nodes // []
l!l
120
MC/DC0%0/1
$tick_nodes // []
$tick_nodes
Truth table50%1/2
A
A= $tick_nodes
Aresult
11
00
827 12 ▶ my @all_peers = ( @{ $tick_peers // [] }, @packet_peers );
Condition50%1/2
$tick_peers // []
l!l
120
MC/DC0%0/1
$tick_peers // []
$tick_peers
Truth table50%1/2
A
A= $tick_peers
Aresult
11
00
828  
829 # Merge packet-derived data with tick-derived data
830 12 my @all_data = grep {defined} ( $tick_data, @packet_data );
831 12 ▶ if ( $debug && ( @all_nodes || @all_peers || @all_data ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug and @all_nodes || @all_peers || @all_data) 0 12 12
Condition11%1/9
$debug and @all_nodes || @all_peers || @all_data
!ll&&!rl&&r
1200
@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
832 0 $self->_emit_log( 'debug',
833 sprintf( "DHT tick+packets: nodes=%d, peers=%d, data=%d", scalar(@all_nodes), scalar(@all_peers), scalar(@all_data) ) );
834 }
835  
836 # If we found new nodes, add them to the frontier of starving torrents
837 12 ▶ if (@all_nodes) {
Branch: 1 branch
BranchTrueFalseTotal
if (@all_nodes) 6 6 12
838 6 for my $t ( values %torrents ) {
839 11 ▶ next if scalar( @{ $t->peer_objects // [] } ) >= 20;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$t->peer_objects // [];} >= 20 0 11 11
Condition50%1/2
$t->peer_objects // []
l!l
110
MC/DC0%0/1
$t->peer_objects // []
$t->peer_objects
Truth table50%1/2
A
A= $t->peer_objects
Aresult
11
00
840 11 $t->add_dht_nodes( \@all_nodes );
841 }
842 }
843  
844 # Dispatch peers to relevant torrents
845 # Net::BitTorrent::DHT::handle_incoming returns (nodes, peers, data)
846 # The 'data' (result) hash contains 'queried_target' which is the infohash
847 # we were looking for when these peers were returned.
848 12 my %dispatched_to;
849 12 for my $d (@all_data) {
850 1 my $ih = $d->{queried_target};
851 1 ▶ if ( $ih && ( my $t = $torrents{$ih} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ih and my $t = $torrents{$ih}) { } 1 0 1
elsif ($debug and $ih) { } 0 0 0
Condition33%1/3
$ih and my $t = $torrents{$ih}
!ll&&!rl&&r
001
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
852 1 ▶ if ( $debug && @all_peers ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug and @all_peers) 0 1 1
Condition33%1/3
$debug and @all_peers
!ll&&!rl&&r
100
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
853 0 $self->_emit_log( 'debug', "Dispatching " . scalar(@all_peers) . " peers to torrent " . unpack( "H*", $ih ) );
854 }
855 1 for my $peer (@all_peers) {
856 0 $t->add_peer($peer);
857 }
858 1 $dispatched_to{$ih} = 1;
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 # Fallback: if peers arrived but no data entry matched, dispatch to torrents in METADATA state that are actively searching (get_peers
866 # responses from bootstrap nodes may not carry queried_target if the response lacks a token field).
867 12 ▶ if ( @all_peers && !%dispatched_to ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@all_peers and not %dispatched_to) 0 12 12
Condition33%1/3
@all_peers and not %dispatched_to
!ll&&!rl&&r
1200
MC/DC0%0/2
@all_peers and not %dispatched_to
@all_peers not %dispatched_to
Truth table33%1/3
A and not(B)
A= @all_peersB= not %dispatched_to
ABresult
0X0
100
111
868 0 for my $t ( grep { $_->state == STATE_METADATA } values %torrents ) {
869 0 ▶ my $ih = $t->infohash_v2 || $t->infohash_v1;
Condition0%0/3
$t->infohash_v2 || $t->infohash_v1
l!l&&r!l&&!r
000
MC/DC0%0/2
$t->infohash_v2 || $t->infohash_v1
$t->infohash_v2 $t->infohash_v1
Truth table0%0/3
A || B
A= $t->infohash_v2B= $t->infohash_v1
ABresult
1X1
011
000
870 0 ▶ next unless $ih;
Branch: 1 branch
BranchTrueFalseTotal
unless $ih 0 0 0
871 0 for my $peer (@all_peers) {
872 0 $t->add_peer($peer);
873 }
874 0 ▶ $self->_emit_log( 'debug', "DHT peer fallback: dispatching " . scalar(@all_peers) . " peers to " . unpack( "H*", $ih ) )
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
875 if $debug;
876 }
877 }
878  
879 # Handle BEP 33, 44, 51 data
880 12 for my $d (@all_data) {
881 1 ▶ if ( exists $d->{samples} ) { # BEP 51
Branch: 1 branch
BranchTrueFalseTotal
if (exists $d->{"samples"}) 0 1 1
882 0 for my $ih ( @{ $d->{samples} } ) {
883 0 my $key = unpack( 'H*', $ih );
884 0 $dht_index{$key} = time();
885 0 ▶ if ( keys %dht_index > 1000 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %dht_index > 1000) 0 0 0
886  
887 # Remove oldest or just random?
888 # For simplicity, remove first key (random in Perl)
889 0 delete $dht_index{ ( keys %dht_index )[0] };
890 }
891 }
892 }
893 1 ▶ if ( exists $d->{v} ) { # BEP 44
Branch: 1 branch
BranchTrueFalseTotal
if (exists $d->{"v"}) 0 1 1
894  
895 # Calculate target (immutable) or use key (mutable)
896 0 my $target = Digest::SHA::sha1( $d->{v} );
897 0 ▶ if ( my $q = delete $dht_queries{$target} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $q = delete $dht_queries{$target}) 0 0 0
898 0 ▶ $q->{cb}->( $d->{v}, $d ) if $q->{cb};
Branch: 1 branch
BranchTrueFalseTotal
if $q->{"cb"} 0 0 0
899 }
900 }
901 1 ▶ if ( exists $d->{sn} ) { # BEP 33
Branch: 1 branch
BranchTrueFalseTotal
if (exists $d->{"sn"}) 1 0 1
902  
903 # Scrape result - find matching torrent
904 1 ▶ if ( my $ih = $d->{queried_target} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ih = $d->{"queried_target"}) 1 0 1
905 1 ▶ if ( my $t = $torrents{$ih} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $t = $torrents{$ih}) 1 0 1
906 1 $t->handle_dht_scrape($d);
907 }
908 }
909 }
910 }
911 }
912  
913 # BEP 14: Periodically announce on local network
914 54 for my $t ( values %torrents ) {
915 64 ▶ if ( rand() < 0.01 ) { # Hack for now
Branch: 1 branch
BranchTrueFalseTotal
if (rand() < "0.01") 1 63 64
916 1 ▶ if ($lpd) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lpd) 1 0 1
917 1 ▶ $lpd->announce( $t->infohash_v2, 6881 ) if $t->infohash_v2;
Branch: 1 branch
BranchTrueFalseTotal
if $t->infohash_v2 0 1 1
918 1 ▶ $lpd->announce( $t->infohash_v1, 6881 ) if $t->infohash_v1;
Branch: 1 branch
BranchTrueFalseTotal
if $t->infohash_v1 1 0 1
919 }
920 }
921 }
922 }
923  
924 0 ▶ method save_state ($path) {
Subroutine save_state: not called CC=6 SCAR=32.6
Pod documented
925 25 ▶ use JSON::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
926 25 ▶ use Path::Tiny qw[path];
Subroutine BEGIN: called CC=1 SCAR=0.0
927 0 my $json = JSON::PP->new->utf8->canonical;
928 0 my %data = ( node_id => $node_id, torrents => {}, );
929 0 my %seen;
930 0 for my $ih ( keys %torrents ) {
931 0 my $t = $torrents{$ih};
932  
933 # prefer v1 key (20 bytes / 40 hex) over v2 (32 bytes / 64 hex)
934 0 ▶ next if length($ih) > 20 && $t->infohash_v1;
Branch: 1 branch
BranchTrueFalseTotal
if length $ih > 20 and $t->infohash_v1 0 0 0
Condition0%0/3
length $ih > 20 and $t->infohash_v1
!ll&&!rl&&r
000
MC/DC0%0/2
length $ih > 20 and $t->infohash_v1
length $ih > 20 $t->infohash_v1
Truth table0%0/3
A and B
A= length $ih > 20B= $t->infohash_v1
ABresult
0X0
100
111
935 0 ▶ next if $seen{ builtin::refaddr($t) }++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{builtin::refaddr($t)}++ 0 0 0
936 0 my $state;
937 0 eval { $state = $t->dump_state() };
938 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
939 0 $self->_emit_log( 'warn', "Failed to dump state for torrent: $@" );
940 0 next;
941 }
942 0 $data{torrents}{ unpack( 'H*', $ih ) } = $state;
943 }
944  
945 # Add integrity checksum to detect tampering
946 0 my $payload = $json->encode( \%data );
947 0 my $sha = Digest::SHA->new(1);
948 0 $sha->add($payload);
949 0 $data{_checksum} = $sha->hexdigest;
950 0 path($path)->spew_utf8( $json->encode( \%data ) );
951 }
952  
953 5 ▶ method load_state ($path) {
Subroutine load_state: called CC=12 SCAR=28.9
Pod documented
954 25 ▶ use JSON::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
955 25 ▶ use Path::Tiny qw[path];
Subroutine BEGIN: called CC=1 SCAR=0.0
956 5 my $json = JSON::PP->new->utf8->canonical;
957 5 ▶ return unless path($path)->exists;
Branch: 1 branch
BranchTrueFalseTotal
unless path($path)->exists 0 5 5
958 5 my $raw = path($path)->slurp_utf8;
959 5 my $data;
960 5 try { $data = $json->decode($raw) }
961 catch ($e) {
962 1 $self->_emit_log( 'error', "Failed to parse state file: $e" );
963 1 return;
964 }
965 4 ▶ return unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 1 3 4
966  
967 # Verify integrity checksum
968 3 ▶ if ( defined $data->{_checksum} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data->{"_checksum"}) 0 3 3
969 0 my $stored = delete $data->{_checksum};
970 0 my $sha = Digest::SHA->new(1);
971 0 $sha->add( $json->encode($data) );
972 0 my $expected = $sha->hexdigest;
973 0 ▶ if ( $expected ne $stored ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expected ne $stored) 0 0 0
974 0 $self->_emit_log( 'warn', 'State file integrity check failed, keeping current state' );
975 0 return;
976 }
977 }
978 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
979 2 $node_id = $data->{node_id};
980 }
981 else {
982 1 $self->_emit_log( 'warn', 'State file missing or invalid node_id, keeping current' );
983 }
984 3 ▶ if ( ref $data->{torrents} eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data->{"torrents"} eq "HASH") 3 0 3
985 3 for my $ih_hex ( keys %{ $data->{torrents} } ) {
986 2 ▶ next unless $ih_hex =~ /^[0-9a-f]{40,64}$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $ih_hex =~ /^[0-9a-f]{40,64}$/iu 1 1 2
987 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
988 0 my $ih = pack( 'H*', $ih_hex );
989 0 ▶ if ( my $t = $torrents{$ih} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $t = $torrents{$ih}) 0 0 0
990 0 $t->load_state( $data->{torrents}{$ih_hex} );
991 }
992 }
993 }
994 }
995  
996 0 ▶ method finished () {
Subroutine finished: not called CC=1 SCAR=6.9
Pod documented
997 0 return [ grep { $_->is_finished } values %torrents ];
998 }
999  
1000 1 ▶ method wait ( $condition = undef, $timeout = undef ) {
Subroutine wait: called CC=7 SCAR=23.7
Pod documented
1001 1 my $start = time();
1002 0 ▶ $condition //= sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1003 0 my @t = values %torrents;
1004 0 ▶ return 1 if !@t;
Branch: 1 branch
BranchTrueFalseTotal
unless @t 0 0 0
1005 0 return ( grep { $_->is_finished } @t ) == @t;
1006 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
1007 1 ▶ while ( !$condition->($self) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$condition($self)) 11 0 11
1008 11 $self->tick(0.1);
1009 11 ▶ if ( defined $timeout && ( time() - $start ) > $timeout ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timeout and &Net::BitTorrent::time() - $start > $timeout) 1 10 11
Condition66%2/3
defined $timeout and &Net::BitTorrent::time() - $start > $timeout
!ll&&!rl&&r
0101
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
1010 1 return 0;
1011 }
1012 10 select( undef, undef, undef, 0.05 );
1013 }
1014 0 return 1;
1015 }
1016 };
1017 #
1018 25 1;
« lib/Net/BitTorrent/DHT.pm ↑ Summary lib/Net/BitTorrent/Transport/TCP.pm »