-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrelay.go
79 lines (60 loc) · 1.97 KB
/
relay.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
package main
import (
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
cmap "github.com/orcaman/concurrent-map"
"log"
"net"
)
type CaptureInfo struct {
fromIface *net.Interface
fromHandle *pcap.Handle
toIface *net.Interface
toHandle *pcap.Handle
macConnections *cmap.ConcurrentMap
}
func Bridge(from *net.Interface, to *net.Interface, macConnections *cmap.ConcurrentMap) {
fromHandle, err := pcap.OpenLive(from.Name, 65536, true, pcap.BlockForever)
if err != nil {
log.Fatalf("Error while connecting to the interface %s: %s\n", from.Name, err.Error())
}
toHandle, err := pcap.OpenLive(to.Name, 65536, true, pcap.BlockForever)
if err != nil {
log.Fatalf("Error while connecting to the interface %s: %s\n", to.Name, err.Error())
}
captureInfo := CaptureInfo{
fromIface: from,
fromHandle: fromHandle,
toIface: to,
toHandle: toHandle,
macConnections: macConnections,
}
packetSource := gopacket.NewPacketSource(fromHandle, fromHandle.LinkType())
handle(&captureInfo, packetSource)
}
func doNotSendPacketBack(packet gopacket.Packet, info *CaptureInfo) bool {
if layer := packet.Layer(layers.LayerTypeEthernet); layer != nil {
layer, _ := layer.(*layers.Ethernet)
info.macConnections.SetIfAbsent(layer.SrcMAC.String(), info.fromIface.Name)
ifaceName, ok := info.macConnections.Get(layer.SrcMAC.String())
/*
to avoid circular packet sending between interfaces,
do not send packets coming from devices this interface is connected with
*/
return ok && ifaceName != info.fromIface.Name
}
return false
}
func handle(info *CaptureInfo, packetSource *gopacket.PacketSource) {
for packet := range packetSource.Packets() {
if doNotSendPacketBack(packet, info) {
continue
}
go PrintPapInfoIfPossible(packet)
err := info.toHandle.WritePacketData(packet.Data())
if err != nil {
log.Printf("Error while sending packet, %s\n", err.Error())
}
}
}