-
Notifications
You must be signed in to change notification settings - Fork 12
/
libpcap.go
104 lines (86 loc) · 2.58 KB
/
libpcap.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
package engine
import (
"errors"
"github.com/fs714/goiftop/accounting"
"github.com/fs714/goiftop/utils/log"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
)
func NewLibPcapEngine(ifaceName, bpfFilter string, direction pcap.Direction, snaplen int32, isDecodeL4 bool, ch chan *accounting.FlowCollection) (engine *LibPcapEngine) {
engine = &LibPcapEngine{
IfaceName: ifaceName,
BpfFilter: bpfFilter,
Direction: direction,
SnapLen: snaplen,
IsDecodeL4: isDecodeL4,
NotifyChannel: ch,
FlowCol: accounting.NewFlowCollection(ifaceName),
FlowColResetInterval: DefaultFlowColResetInterval,
}
return
}
type LibPcapEngine struct {
IfaceName string
BpfFilter string
Direction pcap.Direction
SnapLen int32
IsDecodeL4 bool
NotifyChannel chan *accounting.FlowCollection
FlowCol *accounting.FlowCollection
FlowColResetInterval int64
}
func (e *LibPcapEngine) GetDirection() pcap.Direction {
return e.Direction
}
func (e *LibPcapEngine) GetFlowCollection() *accounting.FlowCollection {
return e.FlowCol
}
func (e *LibPcapEngine) GetResetInterval() int64 {
return e.FlowColResetInterval
}
func (e *LibPcapEngine) GetIsDecodeL4() bool {
return e.IsDecodeL4
}
func (e *LibPcapEngine) GetNotifyChannel() chan *accounting.FlowCollection {
return e.NotifyChannel
}
func (e *LibPcapEngine) StartEngine() (err error) {
go Nofify(e)
err = e.StartCapture()
return
}
func (e *LibPcapEngine) StartCapture() (err error) {
handle, err := pcap.OpenLive(e.IfaceName, e.SnapLen, true, pcap.BlockForever)
if err != nil {
log.Errorf("failed to open live interface %s by LibPcapEngine with err: %s", e.IfaceName, err.Error())
return
}
err = handle.SetBPFFilter(e.BpfFilter)
if err != nil {
log.Errorf("failed to set BPF filter %s by LibPcapEngine with err: %s", e.BpfFilter, err.Error())
return
}
err = handle.SetDirection(e.Direction)
if err != nil {
log.Errorf("failed to set direction by LibPcapEngine with err: %s", err.Error())
return
}
defer handle.Close()
capture := NewCapture(e)
firstLayer := capture.Dec.GetFirstLayerType(handle.LinkType())
if firstLayer == gopacket.LayerTypeZero {
err = errors.New("failed to find first decode layer type")
log.Errorln(err.Error())
return
}
capture.SetFirstLayer(firstLayer)
var data []byte
for {
data, _, err = handle.ZeroCopyReadPacketData()
if err != nil {
log.Errorf("error getting packet: %s", err.Error())
continue
}
capture.DecodeAndAccount(data)
}
}