yggdrasil-go/src/yggdrasil/tun.go

84 lines
1.7 KiB
Go
Raw Normal View History

2017-12-29 07:16:20 +03:00
package yggdrasil
// This manages the tun driver to send/recv packets to/from applications
import ethernet "github.com/songgao/packets/ethernet"
2017-12-29 07:16:20 +03:00
const IPv6_HEADER_LENGTH = 40
type tunInterface interface {
IsTUN() bool
IsTAP() bool
Name() string
Read(to []byte) (int, error)
Write(from []byte) (int, error)
Close() error
}
2017-12-29 07:16:20 +03:00
type tunDevice struct {
2018-01-05 01:37:51 +03:00
core *Core
ndp ndp
2018-01-05 01:37:51 +03:00
send chan<- []byte
recv <-chan []byte
mtu int
iface tunInterface
2017-12-29 07:16:20 +03:00
}
func (tun *tunDevice) init(core *Core) {
2018-01-05 01:37:51 +03:00
tun.core = core
tun.ndp.init(tun)
2017-12-29 07:16:20 +03:00
}
func (tun *tunDevice) write() error {
2018-01-05 01:37:51 +03:00
for {
data := <-tun.recv
if tun.iface.IsTAP() {
var frame ethernet.Frame
frame.Prepare(
tun.ndp.peermac[:6], // Destination MAC address
tun.ndp.mymac[:6], // Source MAC address
ethernet.NotTagged, // VLAN tagging
ethernet.IPv6, // Ethertype
len(data)) // Payload length
copy(frame[14:], data[:])
if _, err := tun.iface.Write(frame); err != nil {
return err
}
} else {
if _, err := tun.iface.Write(data); err != nil {
return err
}
2018-01-05 01:37:51 +03:00
}
util_putBytes(data)
}
2017-12-29 07:16:20 +03:00
}
func (tun *tunDevice) read() error {
2018-01-05 01:37:51 +03:00
buf := make([]byte, tun.mtu)
for {
n, err := tun.iface.Read(buf)
if err != nil {
return err
}
o := 0
if tun.iface.IsTAP() {
o = 14
b := make([]byte, n)
copy(b, buf)
tun.ndp.recv <- b
}
if buf[o]&0xf0 != 0x60 ||
n != 256*int(buf[o+4])+int(buf[o+5])+IPv6_HEADER_LENGTH+o {
2018-01-05 01:37:51 +03:00
// Either not an IPv6 packet or not the complete packet for some reason
//panic("Should not happen in testing")
continue
}
packet := append(util_getBytes(), buf[o:n]...)
2018-01-05 01:37:51 +03:00
tun.send <- packet
}
2017-12-29 07:16:20 +03:00
}
func (tun *tunDevice) close() error {
2018-01-05 01:37:51 +03:00
return tun.iface.Close()
2017-12-29 07:16:20 +03:00
}