| 1 | package Net::BitTorrent::Protocol::BEP03::Bencode v2.1.0 { | ||
| 2 | use v5.40; | ||
| 3 | use Exporter qw[import]; | ||
| 4 | our %EXPORT_TAGS = ( all => [ our @EXPORT_OK = qw[bencode bdecode] ], bencode => [] ); | ||
| 5 | # | ||
| 6 | use constant MAX_BDECODE_DEPTH => 100; | ||
| 7 | use constant MAX_STRING_SIZE => 64 * 1024 * 1024; # 64MB | ||
| 8 | |||
| 9 | sub bencode ( $ref //= return ) { | ||
| 10 | return ( ( ( length $ref ) && $ref =~ m[^([-\+][1-9])?\d*$] ) ? ( 'i' . $ref . 'e' ) : ( length($ref) . ':' . $ref ) ) if !ref $ref; | ||
| 11 | return join( '', 'l', ( map { bencode($_) } @{$ref} ), 'e' ) if ref $ref eq 'ARRAY'; | ||
| 12 | return join( '', 'd', ( map { length($_) . ':' . $_ . bencode( $ref->{$_} ) } sort { $a cmp $b } keys %{$ref} ), 'e' ) if ref $ref eq 'HASH'; | ||
| 13 | return ''; | ||
| 14 | } | ||
| 15 | |||
| 16 | sub bdecode( $string //= return, $k //= 0, $depth = 0 ) { | ||
| 17 | no warnings 'recursion'; # Let me deal with it. | ||
| 18 | die 'bencode nesting depth limit exceeded (max ' . MAX_BDECODE_DEPTH . ' levels)' if $depth > MAX_BDECODE_DEPTH; | ||
| 19 | my $return; | ||
| 20 | if ( $string =~ s[^(0+|[1-9]\d*):][] ) { | ||
| 21 | my $size = $1; | ||
| 22 | die "bencode string too large ($size bytes, max " . MAX_STRING_SIZE . ')' if $size > MAX_STRING_SIZE; | ||
| 23 | $return = '' if $size =~ m[^0+$]; | ||
| 24 | $return .= substr( $string, 0, $size, '' ); | ||
| 25 | return if length $return < $size; | ||
| 26 | return $k ? ( $return, $string ) : $return; # byte string | ||
| 27 | } | ||
| 28 | elsif ( $string =~ s[^i([-\+]?\d+)e][] ) { # integer | ||
| 29 | my $int = $1; | ||
| 30 | $int = () if $int =~ m[^-0] || $int =~ m[^0\d+]; | ||
| 31 | return $k ? ( $int, $string ) : $int; | ||
| 32 | } | ||
| 33 | elsif ( $string =~ s[^l][]s ) { # list without greedy capture | ||
| 34 | while ( $string and $string !~ s[^e][]s ) { | ||
| 35 | ( my ($piece), $string ) = bdecode( $string, 1, $depth + 1 ); | ||
| 36 | push @$return, $piece; | ||
| 37 | } | ||
| 38 | return $k ? ( \@$return, $string ) : \@$return; | ||
| 39 | } | ||
| 40 | elsif ( $string =~ s[^d][]s ) { # dictionary without greedy capture | ||
| 41 | my $pkey; | ||
| 42 | while ( $string and $string !~ s[^e][]s ) { | ||
| 43 | my ( $key, $value ); | ||
| 44 | ( $key, $string ) = bdecode( $string, 1, $depth + 1 ); | ||
| 45 | ( $value, $string ) = bdecode( $string, 1, $depth + 1 ) if $string; | ||
| 46 | die 'malformed dictionary' if defined $pkey && defined $key && $pkey gt $key; # BEP52 | ||
| 47 | $return->{$key} = $value if defined $key; | ||
| 48 | $pkey = $key if defined $key; | ||
| 49 | } | ||
| 50 | return $k ? ( \%$return, $string ) : \%$return; | ||
| 51 | } | ||
| 52 | return; | ||
| 53 | } | ||
| 54 | }; | ||
| 55 | 1; |