forked from ti-mo/conntrack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
event.go
103 lines (86 loc) · 2.33 KB
/
event.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package conntrack
import (
"fmt"
"github.com/mdlayher/netlink"
"github.com/ti-mo/netfilter"
)
// Event holds information about a Conntrack event.
type Event struct {
Type eventType
Flow *Flow
Expect *Expect
}
// eventType is a custom type that describes the Conntrack event type.
type eventType uint8
// List of all types of Conntrack events. This is an internal representation
// unrelated to any message types in the kernel source.
const (
EventUnknown eventType = iota
EventNew
EventUpdate
EventDestroy
EventExpNew
EventExpDestroy
)
// unmarshal unmarshals a Conntrack EventType from a Netfilter header.
func (et *eventType) unmarshal(h netfilter.Header) error {
// Fail when the message is not a conntrack message
if h.SubsystemID == netfilter.NFSubsysCTNetlink {
switch messageType(h.MessageType) {
case ctNew:
// Since the MessageType is only of kind new, get or delete,
// the header's flags are used to distinguish between NEW and UPDATE.
if h.Flags&(netlink.Create|netlink.Excl) != 0 {
*et = EventNew
} else {
*et = EventUpdate
}
case ctDelete:
*et = EventDestroy
default:
return fmt.Errorf(errUnknownEventType, h.MessageType)
}
} else if h.SubsystemID == netfilter.NFSubsysCTNetlinkExp {
switch expMessageType(h.MessageType) {
case ctExpNew:
*et = EventExpNew
case ctExpDelete:
*et = EventExpDestroy
default:
return fmt.Errorf(errUnknownEventType, h.MessageType)
}
} else {
return errNotConntrack
}
return nil
}
// unmarshal unmarshals a Netlink message into an Event structure.
func (e *Event) unmarshal(nlmsg netlink.Message) error {
// Make sure we don't re-use an Event structure
if e.Expect != nil || e.Flow != nil {
return errReusedEvent
}
var err error
// Obtain the nlmsg's Netfilter header and AttributeDecoder.
h, ad, err := netfilter.DecodeNetlink(nlmsg)
if err != nil {
return err
}
// Decode the header to make sure we're dealing with a Conntrack event.
err = e.Type.unmarshal(h)
if err != nil {
return err
}
// Unmarshal Netfilter attributes into the event's Flow or Expect entry.
if h.SubsystemID == netfilter.NFSubsysCTNetlink {
e.Flow = new(Flow)
err = e.Flow.unmarshal(ad)
} else if h.SubsystemID == netfilter.NFSubsysCTNetlinkExp {
e.Expect = new(Expect)
err = e.Expect.unmarshal(ad)
}
if err != nil {
return err
}
return nil
}