diff options
author | Pablo Mazzini <pmazzini@gmail.com> | 2018-04-30 20:26:01 +0100 |
---|---|---|
committer | insomniac <insomniacslk@users.noreply.github.com> | 2018-04-30 21:26:01 +0200 |
commit | c8ffd0e7fcb2eb19d0c9bfefe608302418eae7f9 (patch) | |
tree | d7a8754b678e6bf7b093bab4468854ae0f6c659c | |
parent | d4458d35f16d328a86eb7d0a83ae0576e9d11c77 (diff) |
add NewReplyFromRequest (#51)
-rw-r--r-- | dhcpv6/dhcpv6_test.go | 16 | ||||
-rw-r--r-- | dhcpv6/dhcpv6message.go | 37 |
2 files changed, 53 insertions, 0 deletions
diff --git a/dhcpv6/dhcpv6_test.go b/dhcpv6/dhcpv6_test.go index 2e79f1f..ff89280 100644 --- a/dhcpv6/dhcpv6_test.go +++ b/dhcpv6/dhcpv6_test.go @@ -98,6 +98,22 @@ func TestNewAdvertiseFromSolicit(t *testing.T) { a, err := NewAdvertiseFromSolicit(&s, withServerID) require.NoError(t, err) require.Equal(t, a.(*DHCPv6Message).TransactionID(), s.TransactionID()) + require.Equal(t, a.Type(), ADVERTISE) +} + +func TestNewReplyFromRequest(t *testing.T) { + req := DHCPv6Message{} + req.SetMessage(REQUEST) + req.SetTransactionID(0xabcdef) + cid := OptClientId{} + req.AddOption(&cid) + sid := OptServerId{} + req.AddOption(&sid) + + rep, err := NewReplyFromRequest(&req) + require.NoError(t, err) + require.Equal(t, rep.(*DHCPv6Message).TransactionID(), req.TransactionID()) + require.Equal(t, rep.Type(), REPLY) } // TODO test NewSolicit diff --git a/dhcpv6/dhcpv6message.go b/dhcpv6/dhcpv6message.go index 60b7af5..9bfe932 100644 --- a/dhcpv6/dhcpv6message.go +++ b/dhcpv6/dhcpv6message.go @@ -197,6 +197,43 @@ func NewRequestFromAdvertise(advertise DHCPv6, modifiers ...Modifier) (DHCPv6, e return d, nil } +// NewReplyFromRequest creates a new REPLY packet based on a REQUEST packet. +func NewReplyFromRequest(request DHCPv6, modifiers ...Modifier) (DHCPv6, error) { + if request == nil { + return nil, errors.New("REQUEST cannot be nil") + } + if request.Type() != REQUEST { + return nil, errors.New("The passed REQUEST must have REQUEST type set") + } + req, ok := request.(*DHCPv6Message) + if !ok { + return nil, errors.New("The passed REQUEST must be of DHCPv6Message type") + } + // build REPLY from REQUEST + rep := DHCPv6Message{} + rep.SetMessage(REPLY) + rep.SetTransactionID(req.TransactionID()) + // add Client ID + cid := req.GetOneOption(OPTION_CLIENTID) + if cid == nil { + return nil, errors.New("Client ID cannot be nil in REQUEST when building REPLY") + } + rep.AddOption(cid) + // add Server ID + sid := req.GetOneOption(OPTION_SERVERID) + if sid == nil { + return nil, errors.New("Server ID cannot be nil in REQUEST when building REPLY") + } + rep.AddOption(sid) + + // apply modifiers + d := DHCPv6(&rep) + for _, mod := range modifiers { + d = mod(d) + } + return d, nil +} + func (d *DHCPv6Message) Type() MessageType { return d.messageType } |