| 1 | #!/bin/false | ||
| 2 | # ABSTRACT: DHCPv6 option base class | ||
| 3 | # PODNAME: Net::DHCPv6::Option | ||
| 4 | use strictures 2; | ||
| 5 | |||
| 6 | package Net::DHCPv6::Option; | ||
| 7 | $Net::DHCPv6::Option::VERSION = '0.002'; | ||
| 8 | use Carp qw( croak ); | ||
| 9 | use Net::DHCPv6::Constants; | ||
| 10 | use Net::DHCPv6::X::Truncated; | ||
| 11 | use parent 'Net::DHCPv6::Helpers'; | ||
| 12 | use namespace::clean; | ||
| 13 | my $EMPTY = q(); | ||
| 14 | my $OPT_HDR_SIZE = 4; ## no critic (ValuesAndExpressions::ProhibitMagicNumbers) | ||
| 15 | our $FOLLOW_COMPRESSION = 0; | ||
| 16 | |||
| 17 | sub new { | ||
| 18 | my ( $class, %args ) = @_; | ||
| 19 | croak 'Option->new: code is required' unless defined $args{code}; | ||
| 20 | my $self = { code => $args{code}, data => $args{data} // $EMPTY }; | ||
| 21 | return bless $self, $class; | ||
| 22 | } | ||
| 23 | |||
| 24 | sub code { return shift->{code} } | ||
| 25 | sub data { return shift->{data} } ## no critic (Bangs::ProhibitVagueNames) | ||
| 26 | |||
| 27 | sub type { | ||
| 28 | my $self = shift; | ||
| 29 | return $Net::DHCPv6::Constants::REV_OPTION_CODE{ $self->{code} }; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub as_bytes { | ||
| 33 | my $self = shift; | ||
| 34 | my $payload = $self->{data} // $EMPTY; | ||
| 35 | return pack( 'nn', $self->{code}, CORE::length( $payload ) ) . $payload; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub from_bytes { | ||
| 39 | my ( $class, $bytes ) = @_; | ||
| 40 | Net::DHCPv6::X::Truncated->throw( message => 'Option->from_bytes: need at least 4 bytes for TLV header' ) | ||
| 41 | if !defined $bytes || CORE::length( $bytes ) < $OPT_HDR_SIZE; | ||
| 42 | my $code = unpack( 'n', substr( $bytes, 0, 2 ) ); | ||
| 43 | my $optlen = unpack( 'n', substr( $bytes, 2, 2 ) ); | ||
| 44 | Net::DHCPv6::X::Truncated->throw( message => 'Truncated option TLV payload' ) | ||
| 45 | if $OPT_HDR_SIZE + $optlen > CORE::length( $bytes ); | ||
| 46 | my $payload = substr( $bytes, $OPT_HDR_SIZE, $optlen ); | ||
| 47 | my $remain = substr( $bytes, $OPT_HDR_SIZE + $optlen ); | ||
| 48 | |||
| 49 | require Net::DHCPv6::OptionList; | ||
| 50 | my $class_name = $Net::DHCPv6::OptionList::OPTION_CLASS{$code} | ||
| 51 | || 'Net::DHCPv6::Option::Generic'; | ||
| 52 | my $option = $class_name->from_bytes_inner( $code, $payload ); | ||
| 53 | return ( $option, $remain ); | ||
| 54 | } | ||
| 55 | |||
| 56 | 1; | ||
| 57 | |||
| 58 | __END__ |