| 1 | use v5.40; | ||
| 2 | use feature 'class', 'try'; | ||
| 3 | no warnings 'experimental::class', 'experimental::try'; | ||
| 4 | class Net::BitTorrent::Tracker::UDP v2.1.0 : isa(Net::BitTorrent::Tracker::Base) { | ||
| 5 | use Net::BitTorrent::Protocol::BEP23; | ||
| 6 | use Net::BitTorrent::SSRF qw[is_safe_ip resolve_and_pin]; | ||
| 7 | use IO::Socket::IP; | ||
| 8 | use Crypt::URandom qw[urandom]; | ||
| 9 | use Digest::SHA qw[sha1]; | ||
| 10 | use Config; | ||
| 11 | use constant HAS_64BIT => $Config{ivsize} >= 8; | ||
| 12 | use constant MAX_PENDING_TRANSACTIONS => 100; | ||
| 13 | field $connection_id = HAS_64BIT ? 0 : pack( 'NN', 0, 0 ); | ||
| 14 | field $connection_id_time = 0; | ||
| 15 | field $transaction_id; | ||
| 16 | field $host; | ||
| 17 | field $port; | ||
| 18 | field $resolved_ip; # Cached resolved IP for SSRF-safe retransmissions | ||
| 19 | field $socket; | ||
| 20 | field %pending_transactions; # tid => { type => ..., cb => ..., payload => ..., retries => ..., timestamp => ... } | ||
| 21 | |||
| 22 | sub _split64 ($val) { | ||
| 23 | $val //= 0; | ||
| 24 | if (HAS_64BIT) { return $val } | ||
| 25 | my $hi = int( $val / 4294967296 ); | ||
| 26 | my $lo = $val - ( $hi * 4294967296 ); | ||
| 27 | return ( $hi, $lo ); | ||
| 28 | } | ||
| 29 | ADJUST { | ||
| 30 | if ( $self->url =~ m{^udp://([^:/]+):(\d+)} ) { | ||
| 31 | $host = $1; | ||
| 32 | $port = $2; | ||
| 33 | unless ( $self->ssrf_bypass ) { | ||
| 34 | my ( $ip, $rp ) = resolve_and_pin( $host, $port ); | ||
| 35 | unless ( defined $ip ) { | ||
| 36 | $self->_emit_log( 'error', "UDP tracker blocked by SSRF policy: $host:$port" ); | ||
| 37 | return; | ||
| 38 | } | ||
| 39 | $resolved_ip = $ip; | ||
| 40 | $port = $rp if defined $rp; | ||
| 41 | } | ||
| 42 | else { | ||
| 43 | $resolved_ip = $host; | ||
| 44 | } | ||
| 45 | $socket = IO::Socket::IP->new( Proto => 'udp', Blocking => 0 ) or $self->_emit_log( 'error', "Could not create UDP socket: $!" ); | ||
| 46 | } | ||
| 47 | else { | ||
| 48 | $self->_emit_log( 'error', 'Invalid UDP tracker URL: ' . $self->url ); | ||
| 49 | } | ||
| 50 | } | ||
| 51 | |||
| 52 | method _new_transaction_id () { | ||
| 53 | return $transaction_id = unpack( 'N', urandom(4) ) & 0x7FFFFFFF; | ||
| 54 | } | ||
| 55 | |||
| 56 | method _is_connected () { | ||
| 57 | return defined $connection_id && ( time() - $connection_id_time < 60 ); | ||
| 58 | } | ||
| 59 | |||
| 60 | method tick ( $delta = 0.1 ) { | ||
| 61 | return unless $socket; | ||
| 62 | |||
| 63 | # Check for incoming data | ||
| 64 | while ( $socket->recv( my $buf, 4096 ) ) { | ||
| 65 | my $sender_addr = $socket->peeraddr(); | ||
| 66 | if ( defined $sender_addr && defined $resolved_ip ) { | ||
| 67 | my $sender_ip = unpack( 'N', $sender_addr ); | ||
| 68 | my $expected_ip = unpack( 'N', inet_aton($resolved_ip) ); | ||
| 69 | if ( defined $expected_ip && $sender_ip ne $expected_ip ) { | ||
| 70 | $self->_emit_log( 'debug', 'UDP tracker response from unexpected sender, ignoring' ); | ||
| 71 | next; | ||
| 72 | } | ||
| 73 | } | ||
| 74 | $self->receive_data($buf); | ||
| 75 | } | ||
| 76 | |||
| 77 | # Handle retransmissions | ||
| 78 | my $now = time(); | ||
| 79 | for my $tid ( keys %pending_transactions ) { | ||
| 80 | my $entry = $pending_transactions{$tid}; | ||
| 81 | my $timeout = 15 * ( 2**$entry->{retries} ); | ||
| 82 | if ( $now - $entry->{timestamp} > $timeout ) { | ||
| 83 | if ( $entry->{retries} >= 8 ) { | ||
| 84 | $self->_emit_log( 'error', "UDP transaction $tid timed out after 8 retries" ); | ||
| 85 | delete $pending_transactions{$tid}; | ||
| 86 | next; | ||
| 87 | } | ||
| 88 | $entry->{retries}++; | ||
| 89 | $entry->{timestamp} = $now; | ||
| 90 | $self->_send_packet( $entry->{payload} ); | ||
| 91 | } | ||
| 92 | } | ||
| 93 | } | ||
| 94 | |||
| 95 | method receive_data ($data) { | ||
| 96 | return if length($data) < 8; | ||
| 97 | my ( $action, $tid ) = unpack( 'N N', $data ); | ||
| 98 | my $entry = delete $pending_transactions{$tid}; | ||
| 99 | if ( !$entry ) { | ||
| 100 | $self->_emit_log( 'debug', 'Received UDP packet with unknown transaction ID: ' . $tid ); | ||
| 101 | return; | ||
| 102 | } | ||
| 103 | try { | ||
| 104 | if ( $action == 3 ) { # Error | ||
| 105 | my $msg = substr( $data, 8 ); | ||
| 106 | $msg =~ s/[^\x20-\x7E]/./g; # Sanitize: replace non-printable with dot | ||
| 107 | $self->_emit_log( 'error', 'UDP Tracker error: ' . $msg ); | ||
| 108 | return; | ||
| 109 | } | ||
| 110 | if ( $entry->{type} eq 'connect' ) { | ||
| 111 | if (HAS_64BIT) { | ||
| 112 | ( undef, undef, $connection_id ) = unpack( 'N N Q>', $data ); | ||
| 113 | } | ||
| 114 | else { | ||
| 115 | $connection_id = substr( $data, 8, 8 ); | ||
| 116 | } | ||
| 117 | $connection_id_time = time(); | ||
| 118 | |||
| 119 | # Now that we are connected, trigger the original request | ||
| 120 | if ( $entry->{on_connect} ) { | ||
| 121 | $entry->{on_connect}->(); | ||
| 122 | } | ||
| 123 | } | ||
| 124 | elsif ( $entry->{type} eq 'announce' ) { | ||
| 125 | my $res = $self->parse_announce_response($data); | ||
| 126 | $entry->{cb}->($res) if $entry->{cb}; | ||
| 127 | } | ||
| 128 | elsif ( $entry->{type} eq 'scrape' ) { | ||
| 129 | my $res = $self->parse_scrape_response( $data, $entry->{num_hashes} ); | ||
| 130 | $entry->{cb}->($res) if $entry->{cb}; | ||
| 131 | } | ||
| 132 | } | ||
| 133 | catch ($e) { | ||
| 134 | $self->_emit_log( 'error', 'Error parsing UDP tracker response: ' . $e ); | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 138 | method _send_packet ($payload) { | ||
| 139 | return unless $socket; | ||
| 140 | my $target_ip = $resolved_ip // $host; | ||
| 141 | my $dest = sockaddr_in( $port, inet_aton($target_ip) ); | ||
| 142 | my $sent = $socket->send( $payload, 0, $dest ); | ||
| 143 | $self->_emit_log( 'warn', "UDP send failed: $!" ) unless defined $sent; | ||
| 144 | return $sent; | ||
| 145 | } | ||
| 146 | |||
| 147 | method build_connect_packet () { | ||
| 148 | my $tid = $self->_new_transaction_id(); | ||
| 149 | if (HAS_64BIT) { | ||
| 150 | no warnings 'portable'; | ||
| 151 | return ( $tid, pack( 'Q> N N', 0x41727101980, 0, $tid ) ); | ||
| 152 | } | ||
| 153 | return ( $tid, pack( 'NN N N', 0x417, 0x27101980, 0, $tid ) ); | ||
| 154 | } | ||
| 155 | |||
| 156 | method perform_announce ( $params, $cb = undef ) { | ||
| 157 | if ( scalar keys %pending_transactions >= MAX_PENDING_TRANSACTIONS ) { | ||
| 158 | $self->_emit_log( 'warn', 'UDP tracker pending transaction limit reached' ); | ||
| 159 | return; | ||
| 160 | } | ||
| 161 | if ( !$self->_is_connected() ) { | ||
| 162 | my ( $tid, $pkt ) = $self->build_connect_packet(); | ||
| 163 | $pending_transactions{$tid} = { | ||
| 164 | type => 'connect', | ||
| 165 | payload => $pkt, | ||
| 166 | retries => 0, | ||
| 167 | timestamp => time(), | ||
| 168 | on_connect => sub { $self->perform_announce( $params, $cb ) }, | ||
| 169 | }; | ||
| 170 | $self->_send_packet($pkt); | ||
| 171 | return; | ||
| 172 | } | ||
| 173 | my $pkt = $self->build_announce_packet($params); | ||
| 174 | return unless $pkt; | ||
| 175 | my ($tid) = unpack( 'x8 N', $pkt ); # transaction_id is at offset 12 but after action(4) | ||
| 176 | |||
| 177 | # Wait, action(4) tid(4). So offset 12 is correct for cid(8) + action(4). | ||
| 178 | $tid = unpack( 'N', substr( $pkt, 12, 4 ) ); | ||
| 179 | $pending_transactions{$tid} = { type => 'announce', payload => $pkt, retries => 0, timestamp => time(), cb => $cb, }; | ||
| 180 | $self->_send_packet($pkt); | ||
| 181 | } | ||
| 182 | |||
| 183 | method perform_scrape ( $infohashes, $cb = undef ) { | ||
| 184 | if ( scalar keys %pending_transactions >= MAX_PENDING_TRANSACTIONS ) { | ||
| 185 | $self->_emit_log( 'warn', 'UDP tracker pending transaction limit reached' ); | ||
| 186 | return; | ||
| 187 | } | ||
| 188 | if ( !$self->_is_connected() ) { | ||
| 189 | my ( $tid, $pkt ) = $self->build_connect_packet(); | ||
| 190 | $pending_transactions{$tid} = { | ||
| 191 | type => 'connect', | ||
| 192 | payload => $pkt, | ||
| 193 | retries => 0, | ||
| 194 | timestamp => time(), | ||
| 195 | on_connect => sub { $self->perform_scrape( $infohashes, $cb ) } | ||
| 196 | }; | ||
| 197 | $self->_send_packet($pkt); | ||
| 198 | return; | ||
| 199 | } | ||
| 200 | my $pkt = $self->build_scrape_packet($infohashes); | ||
| 201 | my $tid = unpack( 'N', substr( $pkt, 12, 4 ) ); | ||
| 202 | $pending_transactions{$tid} | ||
| 203 | = { type => 'scrape', payload => $pkt, retries => 0, timestamp => time(), cb => $cb, num_hashes => scalar @$infohashes, }; | ||
| 204 | $self->_send_packet($pkt); | ||
| 205 | } | ||
| 206 | |||
| 207 | method build_announce_packet ($params) { | ||
| 208 | $self->_new_transaction_id(); | ||
| 209 | my %event_map = ( none => 0, completed => 1, started => 2, stopped => 3, ); | ||
| 210 | my $event = $event_map{ $params->{event} // 'none' } // 0; | ||
| 211 | my $ih = $params->{info_hash}; | ||
| 212 | my $ih_len = length($ih); | ||
| 213 | |||
| 214 | # Mandatory key for tracker identification | ||
| 215 | my $key = $params->{key} // ( unpack( 'N', urandom(4) ) & 0x7FFFFFFF ); | ||
| 216 | |||
| 217 | # BEP 52: Support 32-byte infohashes | ||
| 218 | # For UDP trackers, we use the v1 infohash if available, | ||
| 219 | # or truncate/hash the v2 one as per common practice if 32 bytes provided. | ||
| 220 | # REAL BEP 52 UDP trackers expect a modified layout, but standard ones | ||
| 221 | # usually get the 20-byte 'info_hash' (v1 or truncated). | ||
| 222 | my $ih_20 = length($ih) == 32 ? sha1($ih) : $ih; | ||
| 223 | my $tmpl = HAS_64BIT ? 'Q> N N a20 a20 Q> Q> Q> N N N l> n' : 'a8 N N a20 a20 NN NN NN N N N l> n'; | ||
| 224 | return pack( | ||
| 225 | $tmpl, $connection_id, 1, $transaction_id, $ih_20, $params->{peer_id}, _split64( $params->{downloaded} // 0 ), | ||
| 226 | _split64( $params->{left} // 0 ), _split64( $params->{uploaded} // 0 ), $event, 0, # ip | ||
| 227 | $key, $params->{num_want} // -1, $params->{port} | ||
| 228 | ); | ||
| 229 | } | ||
| 230 | |||
| 231 | method parse_announce_response ($data) { | ||
| 232 | return { interval => 0, leechers => 0, seeders => 0, peers => [] } if length($data) < 20; | ||
| 233 | my ( $action, $tid, $interval, $leechers, $seeders ) = unpack( 'N N N N N', $data ); | ||
| 234 | my $peers_raw = substr( $data, 20 ); | ||
| 235 | |||
| 236 | # Cap peer list: max 500 peers per response (UDP datagram is ~4096 bytes anyway) | ||
| 237 | my $peers; | ||
| 238 | if ( length($peers_raw) % 18 == 0 && length($peers_raw) % 6 != 0 ) { | ||
| 239 | $peers_raw = substr( $peers_raw, 0, 500 * 18 ); | ||
| 240 | $peers = Net::BitTorrent::Protocol::BEP23::unpack_peers_ipv6($peers_raw); | ||
| 241 | } | ||
| 242 | else { | ||
| 243 | $peers_raw = substr( $peers_raw, 0, 500 * 6 ); | ||
| 244 | $peers = Net::BitTorrent::Protocol::BEP23::unpack_peers_ipv4($peers_raw); | ||
| 245 | } | ||
| 246 | return { interval => $interval, leechers => $leechers, seeders => $seeders, peers => $peers, }; | ||
| 247 | } | ||
| 248 | |||
| 249 | method build_scrape_packet ($infohashes) { | ||
| 250 | $self->_new_transaction_id(); | ||
| 251 | my @capped = @$infohashes[ 0 .. ( @$infohashes > 70 ? 69 : $#$infohashes ) ]; | ||
| 252 | |||
| 253 | # Validate and truncate each hash to 20 bytes | ||
| 254 | my $ih_data = join( '', map { length($_) == 32 ? sha1($_) : substr( $_, 0, 20 ) } @capped ); | ||
| 255 | my $tmpl = HAS_64BIT ? 'Q> N N a*' : 'a8 N N a*'; | ||
| 256 | return pack( $tmpl, $connection_id, 2, $transaction_id, $ih_data ); | ||
| 257 | } | ||
| 258 | |||
| 259 | method parse_scrape_response ( $data, $num_hashes ) { | ||
| 260 | return { files => [] } if length($data) < 8; | ||
| 261 | my ( $action, $tid ) = unpack( 'N N', $data ); | ||
| 262 | my $results = { files => [] }; | ||
| 263 | my $max_hashes = int( ( length($data) - 8 ) / 12 ); | ||
| 264 | $num_hashes = $max_hashes if $num_hashes > $max_hashes; | ||
| 265 | for ( my $i = 0; $i < $num_hashes; $i++ ) { | ||
| 266 | my ( $seeders, $completed, $leechers ) = unpack( 'N N N', substr( $data, 8 + ( $i * 12 ), 12 ) ); | ||
| 267 | push @{ $results->{files} }, { seeders => $seeders, completed => $completed, leechers => $leechers }; | ||
| 268 | } | ||
| 269 | return $results; | ||
| 270 | } | ||
| 271 | }; | ||
| 272 | 1; |