yggdrasil-go/src/tuntap/tun.go

266 lines
8.1 KiB
Go
Raw Normal View History

package tuntap
2017-12-29 07:16:20 +03:00
// This manages the tun driver to send/recv packets to/from applications
2019-04-23 02:04:22 +03:00
// TODO: Crypto-key routing support
2019-04-23 01:12:13 +03:00
// TODO: Set MTU of session properly
2019-04-23 02:04:22 +03:00
// TODO: Reject packets that exceed session MTU with ICMPv6 for PMTU Discovery
// TODO: Connection timeouts (call Conn.Close() when we want to time out)
// TODO: Don't block in reader on writes that are pending searches
2019-04-23 01:12:13 +03:00
2018-06-13 01:50:08 +03:00
import (
"encoding/hex"
"errors"
"fmt"
2019-01-14 17:25:52 +03:00
"net"
"sync"
"github.com/gologme/log"
2018-06-13 01:50:08 +03:00
"github.com/yggdrasil-network/water"
2018-12-08 04:56:04 +03:00
"github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/config"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
2018-12-08 04:56:04 +03:00
"github.com/yggdrasil-network/yggdrasil-go/src/defaults"
"github.com/yggdrasil-network/yggdrasil-go/src/yggdrasil"
2018-06-13 01:50:08 +03:00
)
2017-12-29 07:16:20 +03:00
2018-05-28 01:31:34 +03:00
const tun_IPv6_HEADER_LENGTH = 40
const tun_ETHER_HEADER_LENGTH = 14
2017-12-29 07:16:20 +03:00
2019-03-29 21:18:31 +03:00
// TunAdapter represents a running TUN/TAP interface and extends the
// yggdrasil.Adapter type. In order to use the TUN/TAP adapter with Yggdrasil,
// you should pass this object to the yggdrasil.SetRouterAdapter() function
// before calling yggdrasil.Start().
type TunAdapter struct {
config *config.NodeState
log *log.Logger
reconfigure chan chan error
listener *yggdrasil.Listener
dialer *yggdrasil.Dialer
addr address.Address
subnet address.Subnet
2019-05-18 00:09:20 +03:00
ckr cryptokey
icmpv6 ICMPv6
mtu int
iface *water.Interface
send chan []byte
mutex sync.RWMutex // Protects the below
addrToConn map[address.Address]*tunConn
subnetToConn map[address.Subnet]*tunConn
dials map[crypto.NodeID][][]byte // Buffer of packets to send after dialing finishes
isOpen bool
2017-12-29 07:16:20 +03:00
}
2018-06-13 00:45:53 +03:00
// Gets the maximum supported MTU for the platform based on the defaults in
// defaults.GetDefaults().
2018-03-03 15:30:54 +03:00
func getSupportedMTU(mtu int) int {
if mtu > defaults.GetDefaults().MaximumIfMTU {
return defaults.GetDefaults().MaximumIfMTU
}
return mtu
}
2019-03-29 21:18:31 +03:00
// Name returns the name of the adapter, e.g. "tun0". On Windows, this may
// return a canonical adapter name instead.
func (tun *TunAdapter) Name() string {
return tun.iface.Name()
}
2019-03-29 21:18:31 +03:00
// MTU gets the adapter's MTU. This can range between 1280 and 65535, although
// the maximum value is determined by your platform. The returned value will
// never exceed that of MaximumMTU().
func (tun *TunAdapter) MTU() int {
return getSupportedMTU(tun.mtu)
}
2019-03-29 21:18:31 +03:00
// IsTAP returns true if the adapter is a TAP adapter (Layer 2) or false if it
// is a TUN adapter (Layer 3).
func (tun *TunAdapter) IsTAP() bool {
return tun.iface.IsTAP()
}
2019-03-29 21:18:31 +03:00
// DefaultName gets the default TUN/TAP interface name for your platform.
func DefaultName() string {
return defaults.GetDefaults().DefaultIfName
}
2019-03-29 21:18:31 +03:00
// DefaultMTU gets the default TUN/TAP interface MTU for your platform. This can
// be as high as MaximumMTU(), depending on platform, but is never lower than 1280.
func DefaultMTU() int {
return defaults.GetDefaults().DefaultIfMTU
}
2019-03-29 21:18:31 +03:00
// DefaultIsTAP returns true if the default adapter mode for the current
// platform is TAP (Layer 2) and returns false for TUN (Layer 3).
func DefaultIsTAP() bool {
return defaults.GetDefaults().DefaultIfTAPMode
}
2019-03-29 21:18:31 +03:00
// MaximumMTU returns the maximum supported TUN/TAP interface MTU for your
// platform. This can be as high as 65535, depending on platform, but is never
// lower than 1280.
func MaximumMTU() int {
return defaults.GetDefaults().MaximumIfMTU
}
// Init initialises the TUN/TAP module. You must have acquired a Listener from
// the Yggdrasil core before this point and it must not be in use elsewhere.
func (tun *TunAdapter) Init(config *config.NodeState, log *log.Logger, listener *yggdrasil.Listener, dialer *yggdrasil.Dialer) {
tun.config = config
tun.log = log
tun.listener = listener
tun.dialer = dialer
tun.addrToConn = make(map[address.Address]*tunConn)
tun.subnetToConn = make(map[address.Subnet]*tunConn)
tun.dials = make(map[crypto.NodeID][][]byte)
2017-12-29 07:16:20 +03:00
}
2019-03-29 21:18:31 +03:00
// Start the setup process for the TUN/TAP adapter. If successful, starts the
// read/write goroutines to handle packets on that interface.
func (tun *TunAdapter) Start() error {
current, _ := tun.config.Get()
if tun.config == nil || tun.listener == nil || tun.dialer == nil {
return errors.New("No configuration available to TUN/TAP")
}
var boxPub crypto.BoxPubKey
boxPubHex, err := hex.DecodeString(current.EncryptionPublicKey)
if err != nil {
return err
}
copy(boxPub[:], boxPubHex)
nodeID := crypto.GetNodeID(&boxPub)
tun.addr = *address.AddrForNodeID(nodeID)
tun.subnet = *address.SubnetForNodeID(nodeID)
tun.mtu = current.IfMTU
ifname := current.IfName
iftapmode := current.IfTAPMode
addr := fmt.Sprintf("%s/%d", net.IP(tun.addr[:]).String(), 8*len(address.GetPrefix())-1)
2019-01-02 21:05:54 +03:00
if ifname != "none" {
if err := tun.setup(ifname, iftapmode, addr, tun.mtu); err != nil {
2019-01-02 21:05:54 +03:00
return err
}
2018-06-03 01:29:06 +03:00
}
2019-01-02 21:05:54 +03:00
if ifname == "none" || ifname == "dummy" {
tun.log.Debugln("Not starting TUN/TAP as ifname is none or dummy")
2019-01-02 21:05:54 +03:00
return nil
2018-05-28 00:35:30 +03:00
}
tun.mutex.Lock()
tun.isOpen = true
tun.send = make(chan []byte, 32) // TODO: is this a sensible value?
2019-05-18 00:29:52 +03:00
tun.reconfigure = make(chan chan error)
tun.mutex.Unlock()
go func() {
for {
e := <-tun.reconfigure
e <- nil
}
}()
go tun.handler()
go tun.reader()
go tun.writer()
2019-04-23 13:37:32 +03:00
tun.icmpv6.Init(tun)
2019-07-06 17:08:17 +03:00
if iftapmode {
go tun.icmpv6.Solicit(tun.addr)
}
2019-05-18 00:09:20 +03:00
tun.ckr.init(tun)
2018-05-28 00:35:30 +03:00
return nil
}
// Start the setup process for the TUN/TAP adapter. If successful, starts the
// read/write goroutines to handle packets on that interface.
func (tun *TunAdapter) Stop() error {
tun.isOpen = false
// TODO: we have nothing that cleanly stops all the various goroutines opened
// by TUN/TAP, e.g. readers/writers, sessions
tun.iface.Close()
return nil
}
2019-05-18 00:29:52 +03:00
// UpdateConfig updates the TUN/TAP module with the provided config.NodeConfig
// and then signals the various module goroutines to reconfigure themselves if
// needed.
func (tun *TunAdapter) UpdateConfig(config *config.NodeConfig) {
tun.log.Debugln("Reloading TUN/TAP configuration...")
tun.config.Replace(*config)
errors := 0
components := []chan chan error{
tun.reconfigure,
tun.ckr.reconfigure,
}
for _, component := range components {
response := make(chan error)
component <- response
if err := <-response; err != nil {
tun.log.Errorln(err)
errors++
}
}
if errors > 0 {
tun.log.Warnln(errors, "TUN/TAP module(s) reported errors during configuration reload")
} else {
tun.log.Infoln("TUN/TAP configuration reloaded successfully")
}
}
func (tun *TunAdapter) handler() error {
for {
// Accept the incoming connection
conn, err := tun.listener.Accept()
if err != nil {
2019-04-21 14:28:46 +03:00
tun.log.Errorln("TUN/TAP connection accept error:", err)
return err
}
if _, err := tun.wrap(conn); err != nil {
// Something went wrong when storing the connection, typically that
// something already exists for this address or subnet
tun.log.Debugln("TUN/TAP handler wrap:", err)
}
}
}
func (tun *TunAdapter) wrap(conn *yggdrasil.Conn) (c *tunConn, err error) {
// Prepare a session wrapper for the given connection
s := tunConn{
tun: tun,
conn: conn,
send: make(chan []byte, 32), // TODO: is this a sensible value?
stop: make(chan struct{}),
alive: make(chan struct{}, 1),
}
c = &s
// Get the remote address and subnet of the other side
remoteNodeID := conn.RemoteAddr()
s.addr = *address.AddrForNodeID(&remoteNodeID)
s.snet = *address.SubnetForNodeID(&remoteNodeID)
// Work out if this is already a destination we already know about
tun.mutex.Lock()
defer tun.mutex.Unlock()
atc, aok := tun.addrToConn[s.addr]
stc, sok := tun.subnetToConn[s.snet]
// If we know about a connection for this destination already then assume it
// is no longer valid and close it
if aok {
atc._close_nomutex()
err = errors.New("replaced connection for address")
} else if sok {
stc._close_nomutex()
err = errors.New("replaced connection for subnet")
}
// Save the session wrapper so that we can look it up quickly next time
// we receive a packet through the interface for this address
tun.addrToConn[s.addr] = &s
tun.subnetToConn[s.snet] = &s
// Start the connection goroutines
go s.reader()
go s.writer()
go s.checkForTimeouts()
// Return
return c, err
2017-12-29 07:16:20 +03:00
}