-
Notifications
You must be signed in to change notification settings - Fork 127
/
tun.go
70 lines (57 loc) · 1.39 KB
/
tun.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
//
// date : 2016-05-13
// author: xjdrew
//
package kone
import (
"net"
"github.com/songgao/water"
"github.com/xjdrew/kone/tcpip"
)
var MTU = 1500
type TunDriver struct {
ifce *water.Interface
filters map[tcpip.IPProtocol]PacketFilter
}
func (tun *TunDriver) Serve() error {
ifce := tun.ifce
filters := tun.filters
buffer := make([]byte, MTU)
for {
n, err := ifce.Read(buffer)
if err != nil {
logger.Errorf("[tun] read failed: %v", err)
return err
}
packet := buffer[:n]
if tcpip.IsIPv4(packet) {
ipPacket := tcpip.IPv4Packet(packet)
protocol := ipPacket.Protocol()
filter := filters[protocol]
if filter == nil {
logger.Noticef("%v > %v protocol %d unsupport", ipPacket.SourceIP(), ipPacket.DestinationIP(), protocol)
continue
}
filter.Filter(ifce, ipPacket)
}
}
}
func (tun *TunDriver) AddRoute(ipNet *net.IPNet) bool {
addRoute(tun.ifce.Name(), ipNet)
logger.Infof("add route %s by %s", ipNet.String(), tun.ifce.Name())
return true
}
func (tun *TunDriver) AddRouteString(val string) bool {
_, subnet, err := net.ParseCIDR(val)
if err != nil {
return false
}
return tun.AddRoute(subnet)
}
func NewTunDriver(ip net.IP, subnet *net.IPNet, filters map[tcpip.IPProtocol]PacketFilter) (*TunDriver, error) {
ifce, err := createTun(ip, subnet.Mask)
if err != nil {
return nil, err
}
return &TunDriver{ifce: ifce, filters: filters}, nil
}