-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
184 lines (153 loc) · 4.14 KB
/
listener.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package buttonoff
import (
"context"
"net"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/pkg/errors"
)
const (
pcapBOOTPFilter = "(port 67 or port 68)"
)
type Listener interface {
UseEventHandler(eh EventHandler) error
}
type PCAPListener struct {
log logrus.FieldLogger
capture *pcapCapture
mu *sync.Mutex
pressEventHandler EventHandler
}
func NewPCAPListener(conf ListenerConfig) (*PCAPListener, error) {
logger := appLogger.WithField("comp", "pcap-listener")
validateErr := checkListenerConfig(conf, logger)
if validateErr != nil {
return nil, validateErr
}
pl := &PCAPListener{
log: logger,
capture: nil,
mu: &sync.Mutex{},
pressEventHandler: nil,
}
capture, captureErr := newPCAPCapture(conf, pl.handleEvent)
if captureErr != nil {
return nil, captureErr
}
pl.capture = capture
return pl, nil
}
func (pl *PCAPListener) Run(ctx context.Context) error {
return pl.capture.Run(ctx)
}
func (pl *PCAPListener) UseEventHandler(eh EventHandler) error {
pl.mu.Lock()
pl.log.Debug("Setting event handler")
pl.pressEventHandler = eh
pl.mu.Unlock()
return nil
}
func (pl *PCAPListener) handleEvent(e Event) error {
pl.mu.Lock()
if pl.pressEventHandler != nil {
pl.log.Debug("Invoking EventHandler for event")
pl.pressEventHandler.HandleEvent(e)
} else {
pl.log.Warn("No handler for event")
}
pl.mu.Unlock()
return nil
}
type pcapCapture struct {
log logrus.FieldLogger
handle *pcap.Handle
callback func(e Event) error
}
func newPCAPCapture(config ListenerConfig, callback func(e Event) error) (*pcapCapture, error) {
logger := appLogger.WithFields(logrus.Fields{
"comp": "pcap-listener.capture",
"device": config.Interface,
})
filteredHandle, err := filteredActiveHandler(config.Interface)
if err != nil {
logger.WithField("device", config.Interface).Error(err)
return nil, err
}
return &pcapCapture{
log: logger,
handle: filteredHandle,
callback: callback,
}, nil
}
func (cap *pcapCapture) Run(ctx context.Context) error {
packetSource := gopacket.NewPacketSource(cap.handle, cap.handle.LinkType())
packets := packetSource.Packets()
cap.log.Debug("running capture processor")
for {
select {
case <-ctx.Done():
return cap.shutdown()
case packet := <-packets:
cap.log.Debug("handling captured packet")
cap.processPacket(packet)
}
}
}
func (cap *pcapCapture) shutdown() error {
cap.log.Debug("closing pcap handle")
cap.handle.Close()
return nil
}
func (cap *pcapCapture) processPacket(packet gopacket.Packet) {
dhcpReqL := packet.Layer(layers.LayerTypeDHCPv4)
if dhcpReqL == nil {
cap.log.Warn("Filtered packet recieved but not decode-able.")
return
}
dhcpReq := dhcpReqL.(*layers.DHCPv4)
// cap.log.Debugf("Recieved a DHCP packet: %v", dhcpReq)
cap.log.Debugf("Packet from client %q", dhcpReq.ClientHWAddr)
event := Event{
HWAddr: dhcpReq.ClientHWAddr.String(),
Timestamp: time.Now(),
}
cap.log.Debugf("Submitting event with listener %v", event)
cap.callback(event)
}
func filteredActiveHandler(device string) (*pcap.Handle, error) {
inactive, err := pcap.NewInactiveHandle(device)
if err != nil {
return nil, errors.Wrapf(err, "could not get inactive handle")
}
promiscErr := inactive.SetPromisc(true) // Listening for BOOTP broadcast packets
if promiscErr != nil {
return nil, errors.Wrap(err, "could not set promiscuous listen")
}
active, err := inactive.Activate()
if err != nil {
return nil, errors.Wrap(err, "could not activate handle")
}
filterErr := active.SetBPFFilter(pcapBOOTPFilter)
if filterErr != nil {
active.Close()
return nil, errors.Wrapf(err, "could not set filter")
}
return active, nil
}
func checkListenerConfig(conf ListenerConfig, log logrus.FieldLogger) error {
ifaces, err := net.Interfaces()
if err != nil {
return errors.Wrap(err, "enumeration of network devices failed")
}
for _, iface := range ifaces {
if iface.Name == conf.Interface {
log.Debugf("Found device in enumerated network interfaces: %s", iface.Name)
break
}
}
return nil
}