blib/lib/Net/uTP/Manager.pm untested

filter: Statementstmt 0.0% 0 / 66 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 6 Podpod n/a totaltotal 0.0% 0 / 97 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 use v5.42;
2 use feature 'class';
3 no warnings 'experimental::class';
4 #
5 class Net::uTP::Manager v1.0.1 {
6 use Net::uTP;
7 use Socket qw[sockaddr_family AF_INET AF_INET6 unpack_sockaddr_in unpack_sockaddr_in6 inet_ntop];
8 use Carp qw[carp croak];
9 #
10 field %connections;
11 field %on;
12 #
13 method on ( $event, $cb ) { push $on{$event}->@*, $cb }
14  
15 method _emit ( $event, @args ) {
16 for my $cb ( $on{$event}->@* ) {
17 try { $cb->(@args) } catch ($e) {
18 carp "uTP Manager event $event failed: $e"
19 };
20 }
21 }
22  
23 method handle_packet ( $data, $sender_addr ) {
24 my ( $port, $ip ) = $self->_unpack_addr($sender_addr);
25 return unless $ip;
26 return if length($data) < 20;
27 my ( $vt, $ext, $conn_id ) = unpack( 'C C n', $data );
28 my $type = $vt & 0x0F;
29 my $key = "$ip:$port:$conn_id";
30 my $utp = $connections{$key};
31 if ( !$utp && $type == 4 ) { # ST_SYN
32 $utp = Net::uTP->new( conn_id_send => $conn_id + 1, conn_id_recv => $conn_id, );
33 $connections{ "$ip:$port:" . ($conn_id) } = $utp;
34 $self->_emit( 'new_connection', $utp, $ip, $port );
35 }
36 if ($utp) {
37 my $res = $utp->receive_packet($data);
38 delete $connections{$key} if $utp->state eq 'CLOSED';
39 return $res;
40 }
41 return undef;
42 }
43  
44 method new_connection ( $ip, $port ) {
45 my $send_id = int rand 65535;
46 my $recv_id = $send_id + 1;
47 my $utp = Net::uTP->new( conn_id_send => $send_id, conn_id_recv => $recv_id );
48 $connections{"$ip:$port:$recv_id"} = $utp;
49 $utp;
50 }
51  
52 method tick ($delta) {
53 my @to_send;
54 for my $key ( keys %connections ) {
55 my $utp = $connections{$key};
56 my $res = $utp->tick($delta);
57 if ($res) {
58 my ( $ip, $port, $cid ) = split( /:/, $key );
59 push @to_send, { ip => $ip, port => $port, data => $res };
60 }
61 delete $connections{$key} if $utp->state eq 'CLOSED';
62 }
63 \@to_send;
64 }
65  
66 method _unpack_addr ($addr) {
67 my $family = eval { sockaddr_family($addr) };
68 return unless defined $family;
69 if ( $family == AF_INET ) {
70 my ( $port, $ip_bin ) = unpack_sockaddr_in($addr);
71 return ( $port, inet_ntop( AF_INET, $ip_bin ) );
72 }
73 elsif ( $family == AF_INET6 ) {
74 my ( $port, $ip_bin ) = unpack_sockaddr_in6($addr);
75 return ( $port, inet_ntop( AF_INET6, $ip_bin ) );
76 }
77 return;
78 }
79 };
80 1;