2017-12-29 07:16:20 +03:00
|
|
|
package yggdrasil
|
|
|
|
|
|
|
|
// This manages the tun driver to send/recv packets to/from applications
|
|
|
|
|
2018-01-06 02:35:59 +03:00
|
|
|
// import water "github.com/songgao/water"
|
2017-12-29 07:16:20 +03:00
|
|
|
|
|
|
|
const IPv6_HEADER_LENGTH = 40
|
|
|
|
|
2018-01-06 02:35:59 +03:00
|
|
|
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
|
|
|
|
send chan<- []byte
|
|
|
|
recv <-chan []byte
|
|
|
|
mtu int
|
2018-01-06 02:35:59 +03:00
|
|
|
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
|
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 _, err := tun.iface.Write(data); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
|
|
|
if buf[0]&0xf0 != 0x60 ||
|
|
|
|
n != 256*int(buf[4])+int(buf[5])+IPv6_HEADER_LENGTH {
|
|
|
|
// 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[:n]...)
|
|
|
|
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
|
|
|
}
|