blib/lib/Net/DHCPv6/Packet.pm untested

filter: Statementstmt 0.0% 0 / 60 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 15 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 116 CC 8 SCAR 25.8
CC
8
Cov
0%
new
42.0
from_bytes
12.0
msg_type
2.0
CRAP 13.2
1 #!/usr/bin/false
2 # ABSTRACT: DHCPv6 packet base class
3 # PODNAME: Net::DHCPv6::Packet
4 package Net::DHCPv6::Packet;
5 $Net::DHCPv6::Packet::VERSION = '0.001';
6 use strictures 2;
7 use Carp qw(croak);
8 use Net::DHCPv6::Constants;
9 use Net::DHCPv6::OptionList;
10 use Net::DHCPv6::Packet::Relay;
11 use Net::DHCPv6::X::BadMessage;
12 use namespace::clean;
13  
14 sub new {
15 my ( $class, @args ) = @_;
16 if ( @args == 1 ) {
17 return $class->from_bytes( $args[0] );
18 }
19 croak 'Packet->new: no arguments' unless @args;
20 my %args = @args;
21 croak 'Packet->new: msg_type is required' unless defined $args{msg_type};
22 croak 'Packet->new: transaction_id is required' unless defined $args{transaction_id};
23 croak 'transaction_id must fit in 24 bits'
24 if $args{transaction_id} < 0 || $args{transaction_id} > 0xFFFFFF;
25 $args{options} = $args{options} // Net::DHCPv6::OptionList->new;
26 my $self = {
27 msg_type => $args{msg_type},
28 transaction_id => $args{transaction_id},
29 options => $args{options},
30 };
31 bless $self, $class;
32 }
33  
34 sub msg_type { shift->{msg_type} }
35 sub transaction_id { shift->{transaction_id} }
36 sub options { shift->{options} }
37  
38 sub add_option {
39 my ( $self, $option ) = @_;
40 $self->{options}->add_option( $option );
41 }
42  
43 sub get_option {
44 my ( $self, $code ) = @_;
45 return $self->{options}->get_option( $code );
46 }
47  
48 sub as_bytes {
49 my $self = shift;
50 my $tid = substr( pack( 'N', $self->{transaction_id} ), 1, 3 );
51 my $opts = $self->{options}->as_bytes;
52 return pack( 'C', $self->{msg_type} ) . $tid . $opts;
53 }
54  
55 sub from_bytes {
56 my ( $class, $bytes ) = @_;
57 Net::DHCPv6::X::BadMessage->throw( message => 'Empty packet data' )
58 unless defined $bytes && CORE::length( $bytes ) >= 4;
59 my $msg_type = unpack( 'C', substr( $bytes, 0, 1 ) );
60  
61 if ( $msg_type == $RELAY_FORW || $msg_type == $RELAY_REPLY ) {
62 return Net::DHCPv6::Packet::Relay->from_bytes( $bytes );
63 }
64  
65 my $tid = unpack( 'N', "\x00" . substr( $bytes, 1, 3 ) );
66 my $opts_bytes = substr( $bytes, 4 );
67  
68 my $subclass = $Net::DHCPv6::Packet::MESSAGE_CLASS{$msg_type} || $class;
69 my $opts = Net::DHCPv6::OptionList->from_bytes( $opts_bytes );
70 my $packet = bless {
71 msg_type => $msg_type,
72 transaction_id => $tid,
73 options => $opts,
74 }, $subclass;
75 return $packet;
76 }
77  
78 sub type {
79 my $self = shift;
80 return $Net::DHCPv6::Constants::REV_MESSAGE_TYPE{ $self->{msg_type} };
81 }
82  
83 sub msg_type_name { shift->type }
84  
85 our %MESSAGE_CLASS;
86  
87 1;
88  
89 __END__