-
Notifications
You must be signed in to change notification settings - Fork 16
/
message.go
71 lines (56 loc) · 1.9 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package netfilter
import (
"github.com/pkg/errors"
"github.com/mdlayher/netlink"
)
// UnmarshalNetlink unmarshals a netlink.Message into a Netfilter Header and Attributes.
func UnmarshalNetlink(msg netlink.Message) (Header, []Attribute, error) {
h, ad, err := DecodeNetlink(msg)
if err != nil {
return Header{}, nil, err
}
attrs, err := decodeAttributes(ad)
if err != nil {
return Header{}, nil, err
}
return h, attrs, nil
}
// DecodeNetlink returns msg's Netfilter header and an AttributeDecoder that can be used
// to iteratively decode all Netlink attributes contained in the message.
func DecodeNetlink(msg netlink.Message) (Header, *netlink.AttributeDecoder, error) {
var h Header
err := h.unmarshal(msg)
if err != nil {
return Header{}, nil, errors.Wrap(err, "unmarshaling netfilter header")
}
ad, err := NewAttributeDecoder(msg.Data[nfHeaderLen:])
if err != nil {
return Header{}, nil, errors.Wrap(err, "creating attribute decoder")
}
return h, ad, nil
}
// MarshalNetlink takes a Netfilter Header and Attributes and returns a netlink.Message.
func MarshalNetlink(h Header, attrs []Attribute) (netlink.Message, error) {
ae := NewAttributeEncoder()
if err := encodeAttributes(ae, attrs); err != nil {
return netlink.Message{}, err
}
return EncodeNetlink(h, ae)
}
// EncodeNetlink generates a netlink.Message based on a given netfilter header h
// and a pre-filled netlink.AttributeEncoder ae.
func EncodeNetlink(h Header, ae *netlink.AttributeEncoder) (netlink.Message, error) {
if ae == nil {
return netlink.Message{}, errNilAttributeEncoder
}
// Encode the AE into a byte slice.
b, err := ae.Encode()
if err != nil {
return netlink.Message{}, err
}
// Allocate space for the marshaled netfilter header.
nlm := netlink.Message{Data: append(make([]byte, nfHeaderLen), b...)}
// marshal error ignored, safe to do if msg Data is initialized.
_ = h.marshal(&nlm)
return nlm, nil
}