From e87114a6e449d7a2e458b5529923e5668dfa3a11 Mon Sep 17 00:00:00 2001 From: Christopher Koch Date: Fri, 28 Dec 2018 20:19:14 -0800 Subject: dhcpv4: simplify option parsing. option's codes and lengths were being parsed twice: once in ParseOption and once in each option type's Parse implementation. Consolidate such that it only happens once. Additionally, only pass data to options that they should parse -- we know the length before the Parse function is called, so the option only gets to see the data it needs to see. Also, use uio.Lexer to simplify parsing code in general. Easier to read and reason about. --- dhcpv4/option_broadcast_address.go | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) (limited to 'dhcpv4/option_broadcast_address.go') diff --git a/dhcpv4/option_broadcast_address.go b/dhcpv4/option_broadcast_address.go index ffa57e3..fdce946 100644 --- a/dhcpv4/option_broadcast_address.go +++ b/dhcpv4/option_broadcast_address.go @@ -3,6 +3,8 @@ package dhcpv4 import ( "fmt" "net" + + "github.com/u-root/u-root/pkg/uio" ) // This option implements the server identifier option @@ -16,21 +18,8 @@ type OptBroadcastAddress struct { // ParseOptBroadcastAddress returns a new OptBroadcastAddress from a byte // stream, or error if any. func ParseOptBroadcastAddress(data []byte) (*OptBroadcastAddress, error) { - if len(data) < 2 { - return nil, ErrShortByteStream - } - code := OptionCode(data[0]) - if code != OptionBroadcastAddress { - return nil, fmt.Errorf("expected code %v, got %v", OptionBroadcastAddress, code) - } - length := int(data[1]) - if length != 4 { - return nil, fmt.Errorf("unexepcted length: expected 4, got %v", length) - } - if len(data) < 6 { - return nil, ErrShortByteStream - } - return &OptBroadcastAddress{BroadcastAddress: net.IP(data[2 : 2+length])}, nil + buf := uio.NewBigEndianBuffer(data) + return &OptBroadcastAddress{BroadcastAddress: net.IP(buf.CopyN(net.IPv4len))}, buf.FinError() } // Code returns the option code. -- cgit v1.2.3