| 1 | use v5.40; | ||
| 2 | use feature 'class'; | ||
| 3 | no warnings 'experimental::class'; | ||
| 4 | use Net::BitTorrent::Emitter; | ||
| 5 | class Net::BitTorrent::Peer v2.1.0 : isa(Net::BitTorrent::Emitter) { | ||
| 6 | use Net::BitTorrent::Types qw[:encryption :state]; | ||
| 7 | use Net::BitTorrent::SSRF qw[is_safe_ip]; | ||
| 8 | field $protocol : param; | ||
| 9 | |||
| 10 | # Instance of Net::BitTorrent::Protocol::BEP03 or subclass | ||
| 11 | field $torrent : param : reader; # Parent Net::BitTorrent::Torrent object | ||
| 12 | field $transport : param : reader; # Net::BitTorrent::Transport::* | ||
| 13 | field $ip : param : reader = undef; | ||
| 14 | field $port : param : reader = undef; | ||
| 15 | field $am_choking : reader = 1; | ||
| 16 | field $am_interested : reader = 0; | ||
| 17 | field $peer_choking : reader = 1; | ||
| 18 | field $peer_interested : reader = 0; | ||
| 19 | field $blocks_inflight : reader = 0; | ||
| 20 | field $bitfield_status : reader : writer = undef; # 'all', 'none', or raw data | ||
| 21 | field $offered_piece = undef; | ||
| 22 | field $bytes_down = 0; | ||
| 23 | field $bytes_up = 0; | ||
| 24 | field $rate_down : reader = 0; | ||
| 25 | field $rate_up : reader = 0; | ||
| 26 | field $reputation : reader = 100; # Start at 100 | ||
| 27 | field $debug : param : reader = 0; | ||
| 28 | field $encryption : param : reader = ENCRYPTION_PREFERRED; # none, preferred, required | ||
| 29 | field $mse : param = undef; | ||
| 30 | field @allowed_fast_set; # Pieces we are allowed to request even if choked | ||
| 31 | field @suggested_pieces; | ||
| 32 | field $pwp_handshake_sent = 0; | ||
| 33 | field $requested_blocks : reader = {}; # Track pending requests "index,begin" => 1 | ||
| 34 | field $last_activity : reader = 0; # Timestamp of last data received | ||
| 35 | field $connected_at : reader = 0; # Timestamp of connection | ||
| 36 | field $_disconnected = 0; # Guard: prevent repeated disconnect | ||
| 37 | use constant REQUEST_TIMEOUT => 30; # Seconds without response before disconnect | ||
| 38 | use constant IDLE_TIMEOUT => 120; # Seconds without any data before disconnect | ||
| 39 | method protocol () {$protocol} | ||
| 40 | method is_encrypted () { defined $mse && $mse->state eq 'PAYLOAD' } | ||
| 41 | method is_seeder () { defined $bitfield_status && $bitfield_status eq 'all' } | ||
| 42 | |||
| 43 | method flags () { | ||
| 44 | my $f = 0; | ||
| 45 | $f |= 0x01 if $self->is_encrypted; | ||
| 46 | $f |= 0x02 if $self->is_seeder; | ||
| 47 | return $f; | ||
| 48 | } | ||
| 49 | ADJUST { | ||
| 50 | $connected_at = time(); | ||
| 51 | $last_activity = $connected_at; | ||
| 52 | $self->set_parent_emitter($torrent); | ||
| 53 | builtin::weaken($torrent) if defined $torrent; | ||
| 54 | if ( $protocol->can('set_peer') ) { | ||
| 55 | $protocol->set_peer($self); | ||
| 56 | } | ||
| 57 | if ( !$mse && $encryption != ENCRYPTION_NONE ) { | ||
| 58 | use Net::BitTorrent::Protocol::MSE; | ||
| 59 | $mse = Net::BitTorrent::Protocol::MSE->new( | ||
| 60 | infohash => $torrent ? ( $torrent->infohash_v1 // $torrent->infohash_v2 ) : undef, | ||
| 61 | is_initiator => 1, # Outgoing | ||
| 62 | allow_plaintext => ( $encryption == ENCRYPTION_PREFERRED ? 1 : 0 ), | ||
| 63 | ); | ||
| 64 | if ( $mse->supported ) { | ||
| 65 | $transport->set_filter($mse); | ||
| 66 | } | ||
| 67 | else { | ||
| 68 | $mse = undef; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | my $weak_self = $self; | ||
| 72 | builtin::weaken($weak_self); | ||
| 73 | $transport->on( | ||
| 74 | 'data', | ||
| 75 | sub ( $emitter, $data ) { | ||
| 76 | $weak_self->receive_data($data) if $weak_self; | ||
| 77 | } | ||
| 78 | ); | ||
| 79 | $transport->on( | ||
| 80 | 'disconnected', | ||
| 81 | sub ( $emitter, @args ) { | ||
| 82 | $weak_self->disconnected() if $weak_self; | ||
| 83 | } | ||
| 84 | ); | ||
| 85 | $transport->on( | ||
| 86 | 'filter_failed', | ||
| 87 | sub ( $emitter, $leftover ) { | ||
| 88 | return unless $weak_self; | ||
| 89 | return if $weak_self->encryption == ENCRYPTION_REQUIRED; | ||
| 90 | $weak_self->_emit_log( 'debug', 'Falling back to plaintext handshake...' ) if $weak_self->debug; | ||
| 91 | |||
| 92 | # We can't easily change $mse from here because it's a field | ||
| 93 | # but we can call a method or just use it. | ||
| 94 | # Actually $mse is in scope but it's a field. | ||
| 95 | # In ADJUST, we can access fields. | ||
| 96 | $mse = undef; | ||
| 97 | $protocol->send_handshake(); | ||
| 98 | $pwp_handshake_sent = 1; | ||
| 99 | } | ||
| 100 | ); | ||
| 101 | $transport->on( | ||
| 102 | 'connected', | ||
| 103 | sub ( $emitter, @args ) { | ||
| 104 | return unless $weak_self; | ||
| 105 | if ($mse) { | ||
| 106 | $weak_self->_emit_log( 'debug', 'Starting MSE handshake...' ) if $weak_self->debug; | ||
| 107 | |||
| 108 | # Handshake is driven by transport filter's write_buffer in tick() | ||
| 109 | } | ||
| 110 | else { | ||
| 111 | $protocol->send_handshake(); | ||
| 112 | $pwp_handshake_sent = 1; | ||
| 113 | } | ||
| 114 | } | ||
| 115 | ); | ||
| 116 | $self->on( | ||
| 117 | 'handshake_complete', | ||
| 118 | sub ( $emitter, @args ) { | ||
| 119 | return unless $weak_self; | ||
| 120 | |||
| 121 | # Some peers need us to be unchoked/interested to talk to us | ||
| 122 | # but we'll stay choked until we have metadata if we want to be safe. | ||
| 123 | # However, we MUST send bitfield/have_none to be protocol compliant. | ||
| 124 | # BEP 03: Send bitfield if we have one | ||
| 125 | if ( $torrent && $torrent->bitfield ) { | ||
| 126 | $protocol->send_bitfield( $torrent->bitfield->data ); | ||
| 127 | } | ||
| 128 | |||
| 129 | # BEP 06: Send HAVE_NONE ONLY if remote supports Fast Extension | ||
| 130 | elsif ( ord( substr( $protocol->reserved, 7, 1 ) ) & 0x04 ) { | ||
| 131 | if ( $protocol->can('send_have_none') ) { | ||
| 132 | $protocol->send_have_none(); | ||
| 133 | } | ||
| 134 | } | ||
| 135 | |||
| 136 | # If in METADATA mode, we don't send unchoke/interested yet | ||
| 137 | return if $torrent && $torrent->state == STATE_METADATA; | ||
| 138 | $weak_self->unchoke(); | ||
| 139 | $weak_self->_check_interest(); | ||
| 140 | |||
| 141 | # BEP 06: Send Allowed Fast set immediately after handshake | ||
| 142 | if ( $protocol->isa('Net::BitTorrent::Protocol::BEP06') ) { | ||
| 143 | my $set = $torrent->get_allowed_fast_set( $weak_self->ip ); | ||
| 144 | for my $idx (@$set) { | ||
| 145 | $protocol->send_allowed_fast($idx); | ||
| 146 | } | ||
| 147 | } | ||
| 148 | if ( $torrent && $torrent->client ) { | ||
| 149 | $torrent->client->_emit( 'peer_connected', $weak_self ); | ||
| 150 | } | ||
| 151 | } | ||
| 152 | ); | ||
| 153 | } | ||
| 154 | |||
| 155 | method send_suggest ($index) { | ||
| 156 | $protocol->send_suggest($index) if $protocol->can('send_suggest'); | ||
| 157 | } | ||
| 158 | |||
| 159 | method send_allowed_fast ($index) { | ||
| 160 | $protocol->send_allowed_fast($index) if $protocol->can('send_allowed_fast'); | ||
| 161 | } | ||
| 162 | |||
| 163 | method on_data ($data) { | ||
| 164 | $self->receive_data($data); | ||
| 165 | } | ||
| 166 | |||
| 167 | method set_protocol ($p) { | ||
| 168 | $protocol = $p; | ||
| 169 | } | ||
| 170 | |||
| 171 | method set_torrent ($t) { | ||
| 172 | $torrent = $t; | ||
| 173 | } | ||
| 174 | |||
| 175 | method receive_data ($data) { | ||
| 176 | $last_activity = time(); | ||
| 177 | $self->_emit_log( 'debug', 'Peer received ' . length($data) . ' bytes of data' ) if $debug; | ||
| 178 | $torrent->can_read( length $data ); | ||
| 179 | $protocol->receive_data($data); | ||
| 180 | } | ||
| 181 | |||
| 182 | method write_buffer () { | ||
| 183 | my $raw = $protocol->write_buffer(); | ||
| 184 | return '' unless length $raw; | ||
| 185 | |||
| 186 | # Rate limiting logic | ||
| 187 | my $allowed = length $raw; | ||
| 188 | if ($torrent) { | ||
| 189 | $allowed = $torrent->can_write( length $raw ); | ||
| 190 | } | ||
| 191 | if ( $allowed <= 0 ) { | ||
| 192 | return 0; # Rate limit: send nothing | ||
| 193 | } | ||
| 194 | elsif ( $allowed < length $raw ) { | ||
| 195 | my $chunk = substr( $raw, 0, $allowed, '' ); | ||
| 196 | return $transport->send_data($chunk); | ||
| 197 | } | ||
| 198 | return $transport->send_data($raw); | ||
| 199 | } | ||
| 200 | |||
| 201 | method handle_hash_request ( $root, $proof_layer, $base_layer, $index, $length ) { | ||
| 202 | my $file = $torrent->storage->get_file_by_root($root); | ||
| 203 | if ( !$file || !$file->merkle ) { | ||
| 204 | $protocol->send_hash_reject( $root, $proof_layer, $base_layer, $index, $length ) if $protocol->can('send_hash_reject'); | ||
| 205 | return; | ||
| 206 | } | ||
| 207 | my $hashes = $file->merkle->get_hashes( $base_layer, $index, $length ); | ||
| 208 | |||
| 209 | # Simplified: no proof nodes added yet | ||
| 210 | $protocol->send_hashes( $root, $proof_layer, $base_layer, $index, $length, $hashes ) if $protocol->can('send_hashes'); | ||
| 211 | } | ||
| 212 | |||
| 213 | method handle_hashes ( $root, $proof_layer, $base_layer, $index, $length, $hashes ) { | ||
| 214 | my $file = $torrent->storage->get_file_by_root($root); | ||
| 215 | return unless $file && $file->merkle; | ||
| 216 | my $node_size = 32; | ||
| 217 | if ( length($hashes) % $node_size != 0 ) { | ||
| 218 | $self->_emit_log( 'warning', 'Invalid hashes length: ' . length($hashes) . ' not a multiple of ' . $node_size ); | ||
| 219 | $self->adjust_reputation(-5); | ||
| 220 | return; | ||
| 221 | } | ||
| 222 | my $num_hashes = length($hashes) / $node_size; | ||
| 223 | |||
| 224 | # BEP 52: index and length refer to the range of nodes at base_layer. | ||
| 225 | # The hashes string contains these nodes concatenated. | ||
| 226 | for ( my $i = 0; $i < $num_hashes; $i++ ) { | ||
| 227 | my $hash = substr( $hashes, $i * $node_size, $node_size ); | ||
| 228 | $file->merkle->set_node( $base_layer, $index + $i, $hash ); | ||
| 229 | } | ||
| 230 | $self->_emit_log( 'debug', "Received and stored $num_hashes hashes for root " . unpack( 'H*', $root ) . " at layer $base_layer" ) if $debug; | ||
| 231 | } | ||
| 232 | |||
| 233 | method handle_hash_reject ( $root, $proof_layer, $base_layer, $index, $length ) { | ||
| 234 | $self->_emit_log( 'debug', 'Peer rejected hash request for root ' . unpack( 'H*', $root ) ) if $debug; | ||
| 235 | } | ||
| 236 | |||
| 237 | method handle_metadata_request ($piece) { | ||
| 238 | $torrent->handle_metadata_request( $self, $piece ); | ||
| 239 | } | ||
| 240 | |||
| 241 | method handle_metadata_data ( $piece, $total_size, $data ) { | ||
| 242 | $torrent->handle_metadata_data( $self, $piece, $total_size, $data ); | ||
| 243 | } | ||
| 244 | |||
| 245 | method handle_metadata_reject ($piece) { | ||
| 246 | $torrent->handle_metadata_reject( $self, $piece ); | ||
| 247 | } | ||
| 248 | |||
| 249 | method handle_pex ( $added, $dropped, $added6, $dropped6 ) { | ||
| 250 | for my $list ( $added, $dropped, $added6, $dropped6 ) { | ||
| 251 | next unless defined $list && ref $list eq 'ARRAY'; | ||
| 252 | |||
| 253 | # Limit PEX entries to prevent resource exhaustion | ||
| 254 | splice( @$list, 100 ) if @$list > 100; | ||
| 255 | } | ||
| 256 | $added //= []; | ||
| 257 | $dropped //= []; | ||
| 258 | $added6 //= []; | ||
| 259 | $dropped6 //= []; | ||
| 260 | for my $p ( @$added, @$added6 ) { | ||
| 261 | next unless ref $p eq 'HASH' && defined $p->{ip} && defined $p->{port}; | ||
| 262 | next if $p->{port} < 1 || $p->{port} > 65535; | ||
| 263 | $torrent->add_peer($p); | ||
| 264 | } | ||
| 265 | } | ||
| 266 | |||
| 267 | method handle_hp_rendezvous ($id) { | ||
| 268 | |||
| 269 | # Remote wants to connect to a node with $id via us. | ||
| 270 | # Find node in our swarm. | ||
| 271 | my $target; | ||
| 272 | for my $p ( values $torrent->peer_objects_hash->%* ) { | ||
| 273 | if ( $p->protocol->can('peer_id') && $p->protocol->peer_id eq $id ) { | ||
| 274 | $target = $p; | ||
| 275 | last; | ||
| 276 | } | ||
| 277 | } | ||
| 278 | if ( $target && exists $target->protocol->remote_extensions->{ut_holepunch} ) { | ||
| 279 | |||
| 280 | # Relay connect instruction to target | ||
| 281 | $target->protocol->send_hp_connect( $self->ip, $self->port ); | ||
| 282 | |||
| 283 | # Acknowledge to source (optional, BEP 55 says relay then ack?) | ||
| 284 | # Actually, BEP says relay 'connect' to target. | ||
| 285 | } | ||
| 286 | else { | ||
| 287 | $protocol->send_hp_error(0x01) if $protocol->can('send_hp_error'); # 0x01 = peer not found | ||
| 288 | } | ||
| 289 | } | ||
| 290 | |||
| 291 | method handle_hp_connect ( $ip, $port ) { | ||
| 292 | unless ( is_safe_ip($ip) ) { | ||
| 293 | $self->_emit_log( 'warn', "HP_CONNECT blocked by SSRF policy: $ip:$port" ) if $debug; | ||
| 294 | return; | ||
| 295 | } | ||
| 296 | unless ( defined $port && $port >= 1 && $port <= 65535 ) { | ||
| 297 | $self->_emit_log( 'warn', "HP_CONNECT rejected: invalid port $port" ) if $debug; | ||
| 298 | return; | ||
| 299 | } | ||
| 300 | state $hp_connect_count = 0; | ||
| 301 | state $hp_connect_reset = time(); | ||
| 302 | my $now = time(); | ||
| 303 | if ( $now - $hp_connect_reset > 60 ) { | ||
| 304 | $hp_connect_count = 0; | ||
| 305 | $hp_connect_reset = $now; | ||
| 306 | } | ||
| 307 | $hp_connect_count++; | ||
| 308 | if ( $hp_connect_count > 10 ) { | ||
| 309 | $self->_emit_log( 'warn', "HP_CONNECT rate limit exceeded, ignoring" ) if $debug; | ||
| 310 | $self->adjust_reputation(-20); | ||
| 311 | return; | ||
| 312 | } | ||
| 313 | $self->_emit_log( 'info', "Instructed to connect to $ip:$port" ) if $debug; | ||
| 314 | |||
| 315 | # Trigger uTP connection | ||
| 316 | $torrent->client->connect_to_peer( $ip, $port, $torrent->infohash_v2 || $torrent->infohash_v1 ); | ||
| 317 | } | ||
| 318 | |||
| 319 | method handle_hp_error ($err) { | ||
| 320 | $self->_emit_log( 'error', 'Received holepunch error: ' . $err ) if $debug; | ||
| 321 | } | ||
| 322 | |||
| 323 | method handle_message ( $id, $payload ) { | ||
| 324 | my $plen = length($payload); | ||
| 325 | |||
| 326 | # Validate payload length per message type (BEP 03) | ||
| 327 | if ( $id == 0 || $id == 1 || $id == 2 || $id == 3 || $id == 14 || $id == 15 ) | ||
| 328 | { # CHOKE, UNCHOKE, INTERESTED, NOT_INTERESTED, HAVE_ALL, HAVE_NONE | ||
| 329 | if ( $plen != 0 ) { | ||
| 330 | $self->_emit_log( 'debug', "Peer message $id expected 0-byte payload, got $plen" ) if $debug; | ||
| 331 | $self->adjust_reputation(-2); | ||
| 332 | return; | ||
| 333 | } | ||
| 334 | } | ||
| 335 | elsif ( $id == 4 || $id == 13 || $id == 17 ) { # HAVE, SUGGEST_PIECE, ALLOWED_FAST | ||
| 336 | if ( $plen != 4 ) { | ||
| 337 | $self->_emit_log( 'debug', "Peer message $id expected 4-byte payload, got $plen" ) if $debug; | ||
| 338 | $self->adjust_reputation(-2); | ||
| 339 | return; | ||
| 340 | } | ||
| 341 | } | ||
| 342 | elsif ( $id == 6 || $id == 16 ) { # REQUEST, REJECT | ||
| 343 | if ( $plen != 12 ) { | ||
| 344 | $self->_emit_log( 'debug', "Peer message $id expected 12-byte payload, got $plen" ) if $debug; | ||
| 345 | $self->adjust_reputation(-2); | ||
| 346 | return; | ||
| 347 | } | ||
| 348 | } | ||
| 349 | elsif ( $id == 7 ) { # PIECE | ||
| 350 | if ( $plen < 8 ) { | ||
| 351 | $self->_emit_log( 'debug', "Peer PIECE message too short ($plen bytes)" ) if $debug; | ||
| 352 | $self->adjust_reputation(-2); | ||
| 353 | return; | ||
| 354 | } | ||
| 355 | } | ||
| 356 | |||
| 357 | # warn ' [DEBUG] Peer ' . ($socket ? $socket->peerhost : 'sim') . " sent message ID $id (len " . length($payload) . ")\n"; | ||
| 358 | if ( $id == 0 ) { # CHOKE | ||
| 359 | $peer_choking = 1; | ||
| 360 | $self->_emit('choked'); | ||
| 361 | } | ||
| 362 | elsif ( $id == 1 ) { # UNCHOKE | ||
| 363 | $peer_choking = 0; | ||
| 364 | $self->_emit('unchoked'); | ||
| 365 | $self->_request_next_block(); | ||
| 366 | } | ||
| 367 | elsif ( $id == 2 ) { # INTERESTED | ||
| 368 | $peer_interested = 1; | ||
| 369 | $self->_emit('interested'); | ||
| 370 | } | ||
| 371 | elsif ( $id == 3 ) { # NOT_INTERESTED | ||
| 372 | $peer_interested = 0; | ||
| 373 | $self->_emit('not_interested'); | ||
| 374 | } | ||
| 375 | elsif ( $id == 4 ) { # HAVE | ||
| 376 | my $index = unpack( 'N', $payload ); | ||
| 377 | my $num_pieces = $torrent->bitfield ? $torrent->bitfield->size : 0; | ||
| 378 | if ( !defined $num_pieces || $num_pieces == 0 || $index >= $num_pieces ) { | ||
| 379 | $self->_emit_log( 'debug', "Peer sent HAVE with out-of-range index $index (num_pieces=$num_pieces)" ) if $debug; | ||
| 380 | $self->adjust_reputation(-2); | ||
| 381 | return; | ||
| 382 | } | ||
| 383 | $torrent->update_peer_have( $self, $index ); | ||
| 384 | |||
| 385 | # BEP 16: If we see this peer (or others) have our offered piece, | ||
| 386 | # we can offer a new one. (Simplified global check) | ||
| 387 | if ( defined $offered_piece && $index == $offered_piece ) { | ||
| 388 | $offered_piece = undef; | ||
| 389 | } | ||
| 390 | $self->_check_interest(); | ||
| 391 | } | ||
| 392 | elsif ( $id == 5 ) { # BITFIELD | ||
| 393 | $bitfield_status = $payload; | ||
| 394 | $torrent->set_peer_bitfield( $self, $payload ); | ||
| 395 | $self->_emit( bitfield => $torrent->peer_bitfields->{$self} ); | ||
| 396 | |||
| 397 | # BEP 16: If superseeding, we don't send our real bitfield. | ||
| 398 | # Instead, we wait for interest and then offer pieces. | ||
| 399 | $self->_check_interest(); | ||
| 400 | } | ||
| 401 | elsif ( $id == 6 ) { # REQUEST | ||
| 402 | my ( $index, $begin, $len ) = unpack( 'N N N', $payload ); | ||
| 403 | my $num_pieces = $torrent->bitfield ? $torrent->bitfield->size : 0; | ||
| 404 | my $piece_len = $torrent->metadata->{info}{'piece length'} // 16384; | ||
| 405 | if ( $num_pieces == 0 || $index >= $num_pieces ) { | ||
| 406 | $self->_emit_log( 'debug', "Peer REQUEST with out-of-range index $index" ) if $debug; | ||
| 407 | return; | ||
| 408 | } | ||
| 409 | if ( $len == 0 || $len > 131072 ) { # 2^17 = 128 KiB max block | ||
| 410 | $self->_emit_log( 'debug', "Peer REQUEST with invalid len $len" ) if $debug; | ||
| 411 | return; | ||
| 412 | } | ||
| 413 | if ( $begin + $len > $piece_len ) { | ||
| 414 | $self->_emit_log( 'debug', 'Peer REQUEST extends beyond piece boundary' ) if $debug; | ||
| 415 | return; | ||
| 416 | } | ||
| 417 | $self->_handle_request( $index, $begin, $len ); | ||
| 418 | } | ||
| 419 | elsif ( $id == 7 ) { # PIECE | ||
| 420 | my ( $index, $begin ) = unpack( 'N N', substr( $payload, 0, 8, '' ) ); | ||
| 421 | $self->_handle_piece_data( $index, $begin, $payload ); | ||
| 422 | } | ||
| 423 | elsif ( $id == 13 ) { # SUGGEST_PIECE | ||
| 424 | my $index = unpack( 'N', $payload ); | ||
| 425 | push @suggested_pieces, $index if scalar @suggested_pieces < 100 && !grep { $_ == $index } @suggested_pieces; | ||
| 426 | $self->_check_interest(); | ||
| 427 | } | ||
| 428 | elsif ( $id == 14 ) { # HAVE_ALL | ||
| 429 | $bitfield_status = 'all'; | ||
| 430 | $torrent->set_peer_have_all($self); | ||
| 431 | $self->_emit('have_all'); | ||
| 432 | $self->_check_interest(); | ||
| 433 | } | ||
| 434 | elsif ( $id == 15 ) { # HAVE_NONE | ||
| 435 | $bitfield_status = 'none'; | ||
| 436 | $torrent->set_peer_have_none($self); | ||
| 437 | $self->_emit('have_none'); | ||
| 438 | } | ||
| 439 | elsif ( $id == 16 ) { # REJECT | ||
| 440 | my ( $index, $begin, $len ) = unpack( 'N N N', $payload ); | ||
| 441 | $self->_handle_reject( $index, $begin, $len ); | ||
| 442 | } | ||
| 443 | elsif ( $id == 17 ) { # ALLOWED_FAST | ||
| 444 | my $index = unpack( 'N', $payload ); | ||
| 445 | my $max_allowed = $torrent->bitfield ? ( $torrent->bitfield->size < 10 ? $torrent->bitfield->size : 10 ) : 10; | ||
| 446 | push @allowed_fast_set, $index if scalar @allowed_fast_set < $max_allowed && !grep { $_ == $index } @allowed_fast_set; | ||
| 447 | $self->_check_interest(); | ||
| 448 | } | ||
| 449 | } | ||
| 450 | |||
| 451 | method _handle_reject ( $index, $begin, $len ) { | ||
| 452 | my $key = "$index,$begin"; | ||
| 453 | $blocks_inflight-- if delete $self->requested_blocks->{$key} && $blocks_inflight > 0; | ||
| 454 | delete $torrent->blocks_pending->{$index}{$begin}; | ||
| 455 | $self->_request_next_block(); | ||
| 456 | } | ||
| 457 | |||
| 458 | method _check_interest () { | ||
| 459 | if ( $torrent->is_superseed ) { | ||
| 460 | $self->_check_superseed(); | ||
| 461 | } | ||
| 462 | if ( !$am_interested ) { | ||
| 463 | my $bitfield = $torrent->bitfield; | ||
| 464 | my $p_bfs = $torrent->peer_bitfields; | ||
| 465 | my $p_bf = $p_bfs->{$self}; | ||
| 466 | my $has_new = 0; | ||
| 467 | if ($p_bf) { | ||
| 468 | for ( my $i = 0; $i < $bitfield->size; $i++ ) { | ||
| 469 | if ( !$bitfield->get($i) && $p_bf->get($i) ) { | ||
| 470 | $has_new = 1; | ||
| 471 | last; | ||
| 472 | } | ||
| 473 | } | ||
| 474 | } | ||
| 475 | if ($has_new) { | ||
| 476 | $am_interested = 1; | ||
| 477 | $protocol->send_message(2); # INTERESTED | ||
| 478 | } | ||
| 479 | } | ||
| 480 | } | ||
| 481 | |||
| 482 | method _check_superseed () { | ||
| 483 | return if defined $offered_piece; | ||
| 484 | |||
| 485 | # Pick a piece to offer | ||
| 486 | my $bitfield = $torrent->bitfield; | ||
| 487 | my $p_bfs = $torrent->peer_bitfields; | ||
| 488 | my $p_bf = $p_bfs->{$self}; | ||
| 489 | return unless $p_bf; | ||
| 490 | for ( my $i = 0; $i < $bitfield->size; $i++ ) { | ||
| 491 | if ( $bitfield->get($i) && !$p_bf->get($i) ) { | ||
| 492 | $offered_piece = $i; | ||
| 493 | $protocol->send_message( 4, pack( 'N', $i ) ); # HAVE | ||
| 494 | last; | ||
| 495 | } | ||
| 496 | } | ||
| 497 | } | ||
| 498 | |||
| 499 | method _request_next_block () { | ||
| 500 | while ( $blocks_inflight < 5 ) { | ||
| 501 | my $req = $torrent->get_next_request($self); | ||
| 502 | if ($req) { | ||
| 503 | |||
| 504 | # BEP 06: Can request if not choked OR if piece is in allowed_fast_set | ||
| 505 | if ( !$peer_choking || $self->is_allowed_fast( $req->{index} ) ) { | ||
| 506 | $protocol->send_message( 6, pack( 'N N N', $req->{index}, $req->{begin}, $req->{length} ) ); | ||
| 507 | $blocks_inflight++; | ||
| 508 | $self->requested_blocks->{"$req->{index},$req->{begin}"} = 1; | ||
| 509 | } | ||
| 510 | else { | ||
| 511 | # We picked a piece but we are choked and it's not fast-allowed. | ||
| 512 | # We must un-pending it so others can pick it. | ||
| 513 | delete $torrent->blocks_pending->{ $req->{index} }{ $req->{begin} }; | ||
| 514 | last; | ||
| 515 | } | ||
| 516 | } | ||
| 517 | else { | ||
| 518 | last; | ||
| 519 | } | ||
| 520 | } | ||
| 521 | } | ||
| 522 | |||
| 523 | method is_allowed_fast ($index) { | ||
| 524 | return grep { $_ == $index } @allowed_fast_set; | ||
| 525 | } | ||
| 526 | |||
| 527 | method _handle_request ( $index, $begin, $len ) { | ||
| 528 | return if $am_choking; | ||
| 529 | |||
| 530 | # Reputation checks | ||
| 531 | # Do we even have this piece? | ||
| 532 | if ( !$torrent->bitfield->get($index) ) { | ||
| 533 | $self->adjust_reputation(-5); | ||
| 534 | return; | ||
| 535 | } | ||
| 536 | |||
| 537 | # Does the peer already have this piece? | ||
| 538 | my $p_bf = $torrent->peer_bitfields->{$self}; | ||
| 539 | if ( $p_bf && $p_bf->get($index) ) { | ||
| 540 | $self->adjust_reputation(-5); | ||
| 541 | return; | ||
| 542 | } | ||
| 543 | my $piece_len = $torrent->metadata->{info}{'piece length'} // 16384; | ||
| 544 | my $abs_offset = ( $index * $piece_len ) + $begin; | ||
| 545 | my $data = $torrent->storage->read_global( $abs_offset, $len ); | ||
| 546 | if ($data) { | ||
| 547 | $bytes_up += length($data); | ||
| 548 | $protocol->send_message( 7, pack( 'N N', $index, $begin ) . $data ); | ||
| 549 | } | ||
| 550 | } | ||
| 551 | |||
| 552 | method _handle_piece_data ( $index, $begin, $data ) { | ||
| 553 | $self->_emit_log( 'debug', 'Received ' . length($data) . " bytes for piece $index at $begin" ) if $debug; | ||
| 554 | if ( length($data) == 0 || length($data) > 131072 ) { | ||
| 555 | $self->_emit_log( 'debug', "Invalid PIECE data length: " . length($data) ) if $debug; | ||
| 556 | $self->adjust_reputation(-5); | ||
| 557 | return; | ||
| 558 | } | ||
| 559 | $bytes_down += length($data); | ||
| 560 | my $key = "$index,$begin"; | ||
| 561 | if ( delete $self->requested_blocks->{$key} ) { | ||
| 562 | $blocks_inflight-- if $blocks_inflight > 0; | ||
| 563 | } | ||
| 564 | else { | ||
| 565 | $self->_emit_log( 'warning', "Received unsolicited PIECE for $key" ) if $debug; | ||
| 566 | $self->adjust_reputation(-10); | ||
| 567 | } | ||
| 568 | my $status = $torrent->receive_block( $self, $index, $begin, $data ); | ||
| 569 | if ( $status == 1 ) { | ||
| 570 | |||
| 571 | # Verified and saved | ||
| 572 | } | ||
| 573 | elsif ( $status == -1 ) { | ||
| 574 | |||
| 575 | # Failed verification | ||
| 576 | } | ||
| 577 | $self->_request_next_block(); | ||
| 578 | } | ||
| 579 | |||
| 580 | method disconnected () { | ||
| 581 | return if $_disconnected; | ||
| 582 | $_disconnected = 1; | ||
| 583 | $torrent->peer_disconnected($self) if $torrent; | ||
| 584 | $transport->close() if $transport && $transport->can('close'); | ||
| 585 | $self->_emit('disconnected'); | ||
| 586 | } | ||
| 587 | |||
| 588 | method unchoke () { | ||
| 589 | $am_choking = 0; | ||
| 590 | $protocol->send_message(1); # UNCHOKE | ||
| 591 | } | ||
| 592 | |||
| 593 | method choke () { | ||
| 594 | $am_choking = 1; | ||
| 595 | $protocol->send_message(0); # CHOKE | ||
| 596 | } | ||
| 597 | |||
| 598 | method interested () { | ||
| 599 | $am_interested = 1; | ||
| 600 | $protocol->send_message(2); # INTERESTED | ||
| 601 | } | ||
| 602 | |||
| 603 | method not_interested () { | ||
| 604 | $am_interested = 0; | ||
| 605 | $protocol->send_message(3); # NOT_INTERESTED | ||
| 606 | } | ||
| 607 | |||
| 608 | method request ( $index, $begin, $len ) { | ||
| 609 | $blocks_inflight++; | ||
| 610 | $self->requested_blocks->{"$index,$begin"} = 1; | ||
| 611 | $protocol->send_message( 6, pack( 'N N N', $index, $begin, $len ) ); | ||
| 612 | } | ||
| 613 | |||
| 614 | method cancel_request ( $index, $begin ) { | ||
| 615 | my $key = "$index,$begin"; | ||
| 616 | if ( delete $self->requested_blocks->{$key} ) { | ||
| 617 | $blocks_inflight-- if $blocks_inflight > 0; | ||
| 618 | } | ||
| 619 | } | ||
| 620 | |||
| 621 | method tick () { | ||
| 622 | return if $_disconnected; | ||
| 623 | |||
| 624 | # Zombie peer detection: disconnect if no activity for too long | ||
| 625 | my $idle = time() - $last_activity; | ||
| 626 | if ( $blocks_inflight > 0 && $idle > REQUEST_TIMEOUT ) { | ||
| 627 | $self->_emit_log( 'warn', "Request timeout: $ip:$port silent for ${idle}s with $blocks_inflight inflight" ) if $debug; | ||
| 628 | $self->disconnected(); | ||
| 629 | return; | ||
| 630 | } | ||
| 631 | if ( $idle > IDLE_TIMEOUT && $protocol->state eq 'OPEN' ) { | ||
| 632 | $self->_emit_log( 'debug', "Idle timeout: $ip:$port silent for ${idle}s" ) if $debug; | ||
| 633 | $self->disconnected(); | ||
| 634 | return; | ||
| 635 | } | ||
| 636 | |||
| 637 | # Simple moving average / decay | ||
| 638 | $rate_down = ( $rate_down * 0.8 ) + ( $bytes_down * 0.2 ); | ||
| 639 | $rate_up = ( $rate_up * 0.8 ) + ( $bytes_up * 0.2 ); | ||
| 640 | $bytes_down = 0; | ||
| 641 | $bytes_up = 0; | ||
| 642 | $transport->tick() if $transport->can('tick'); | ||
| 643 | |||
| 644 | # MSE Transition Check | ||
| 645 | if ( $mse && $mse->state eq 'PAYLOAD' && !$pwp_handshake_sent ) { | ||
| 646 | $self->_emit_log( 'debug', 'MSE handshake complete, sending protocol handshake...' ) if $debug; | ||
| 647 | $protocol->send_handshake(); | ||
| 648 | $pwp_handshake_sent = 1; | ||
| 649 | } | ||
| 650 | |||
| 651 | # Fatal Protocol Error Check | ||
| 652 | if ( $protocol->state eq 'CLOSED' ) { | ||
| 653 | $self->_emit_log( 'error', "Fatal protocol error from $ip:$port. Disconnecting." ) if $debug; | ||
| 654 | $self->disconnected(); | ||
| 655 | return; | ||
| 656 | } | ||
| 657 | $self->write_buffer(); | ||
| 658 | } | ||
| 659 | |||
| 660 | method adjust_reputation ($delta) { | ||
| 661 | return if $_disconnected; | ||
| 662 | $reputation += $delta; | ||
| 663 | $reputation = 0 if $reputation < 0; | ||
| 664 | $reputation = 100 if $reputation > 100; | ||
| 665 | if ( $reputation <= 20 ) { | ||
| 666 | $self->_emit_log( 'error', "Blacklisting peer $ip:$port due to low reputation ($reputation)" ) if $debug; | ||
| 667 | $self->disconnected(); | ||
| 668 | } | ||
| 669 | } | ||
| 670 | }; | ||
| 671 | 1; |