Refactoring: move tuntap and icmpv6 into separate package

This commit is contained in:
Neil Alexander 2019-03-28 00:30:25 +00:00
parent 67c670ab4c
commit 0b494a8255
No known key found for this signature in database
GPG key ID: A02A2019A2BB0944
20 changed files with 307 additions and 240 deletions

View file

@ -1,18 +1,36 @@
package yggdrasil
import (
"github.com/gologme/log"
"github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/config"
)
// Defines the minimum required struct members for an adapter type (this is
// now the base type for tunAdapter in tun.go)
// now the base type for TunAdapter in tun.go)
type Adapter struct {
core *Core
send chan<- []byte
recv <-chan []byte
reconfigure chan chan error
adapterImplementation
Core *Core
Send chan<- []byte
Recv <-chan []byte
Reconfigure chan chan error
}
// Defines the minimum required functions for an adapter type
type adapterImplementation interface {
Init(*config.NodeState, *log.Logger, chan<- []byte, <-chan []byte)
Name() string
MTU() int
IsTAP() bool
Start(address.Address, address.Subnet) error
Read() error
Write() error
Close() error
}
// Initialises the adapter.
func (adapter *Adapter) init(core *Core, send chan<- []byte, recv <-chan []byte) {
adapter.core = core
adapter.send = send
adapter.recv = recv
adapter.reconfigure = make(chan chan error, 1)
func (adapter Adapter) Init(config *config.NodeState, log *log.Logger, send chan<- []byte, recv <-chan []byte) {
adapter.Send = send
adapter.Recv = recv
adapter.Reconfigure = make(chan chan error, 1)
}

View file

@ -16,7 +16,6 @@ import (
"github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
"github.com/yggdrasil-network/yggdrasil-go/src/defaults"
)
// TODO: Add authentication
@ -58,19 +57,17 @@ func (a *admin) init(c *Core) {
go func() {
for {
e := <-a.reconfigure
a.core.configMutex.RLock()
if a.core.config.AdminListen != a.core.configOld.AdminListen {
a.listenaddr = a.core.config.AdminListen
current, previous := a.core.config.Get()
if current.AdminListen != previous.AdminListen {
a.listenaddr = current.AdminListen
a.close()
a.start()
}
a.core.configMutex.RUnlock()
e <- nil
}
}()
a.core.configMutex.RLock()
a.listenaddr = a.core.config.AdminListen
a.core.configMutex.RUnlock()
current, _ := a.core.config.Get()
a.listenaddr = current.AdminListen
a.addHandler("list", []string{}, func(in admin_info) (admin_info, error) {
handlers := make(map[string]interface{})
for _, handler := range a.handlers {
@ -171,47 +168,47 @@ func (a *admin) init(c *Core) {
}, errors.New("Failed to remove peer")
}
})
a.addHandler("getTunTap", []string{}, func(in admin_info) (r admin_info, e error) {
defer func() {
if err := recover(); err != nil {
r = admin_info{"none": admin_info{}}
e = nil
}
}()
/* a.addHandler("getTunTap", []string{}, func(in admin_info) (r admin_info, e error) {
defer func() {
if err := recover(); err != nil {
r = admin_info{"none": admin_info{}}
e = nil
}
}()
return admin_info{
a.core.router.tun.iface.Name(): admin_info{
"tap_mode": a.core.router.tun.iface.IsTAP(),
"mtu": a.core.router.tun.mtu,
},
}, nil
})
a.addHandler("setTunTap", []string{"name", "[tap_mode]", "[mtu]"}, func(in admin_info) (admin_info, error) {
// Set sane defaults
iftapmode := defaults.GetDefaults().DefaultIfTAPMode
ifmtu := defaults.GetDefaults().DefaultIfMTU
// Has TAP mode been specified?
if tap, ok := in["tap_mode"]; ok {
iftapmode = tap.(bool)
}
// Check we have enough params for MTU
if mtu, ok := in["mtu"]; ok {
if mtu.(float64) >= 1280 && ifmtu <= defaults.GetDefaults().MaximumIfMTU {
ifmtu = int(in["mtu"].(float64))
}
}
// Start the TUN adapter
if err := a.startTunWithMTU(in["name"].(string), iftapmode, ifmtu); err != nil {
return admin_info{}, errors.New("Failed to configure adapter")
} else {
return admin_info{
a.core.router.tun.iface.Name(): admin_info{
"tap_mode": a.core.router.tun.iface.IsTAP(),
"mtu": ifmtu,
"mtu": a.core.router.tun.mtu,
},
}, nil
}
})
})
a.addHandler("setTunTap", []string{"name", "[tap_mode]", "[mtu]"}, func(in admin_info) (admin_info, error) {
// Set sane defaults
iftapmode := defaults.GetDefaults().DefaultIfTAPMode
ifmtu := defaults.GetDefaults().DefaultIfMTU
// Has TAP mode been specified?
if tap, ok := in["tap_mode"]; ok {
iftapmode = tap.(bool)
}
// Check we have enough params for MTU
if mtu, ok := in["mtu"]; ok {
if mtu.(float64) >= 1280 && ifmtu <= defaults.GetDefaults().MaximumIfMTU {
ifmtu = int(in["mtu"].(float64))
}
}
// Start the TUN adapter
if err := a.startTunWithMTU(in["name"].(string), iftapmode, ifmtu); err != nil {
return admin_info{}, errors.New("Failed to configure adapter")
} else {
return admin_info{
a.core.router.tun.iface.Name(): admin_info{
"tap_mode": a.core.router.tun.iface.IsTAP(),
"mtu": ifmtu,
},
}, nil
}
})*/
a.addHandler("getMulticastInterfaces", []string{}, func(in admin_info) (admin_info, error) {
var intfs []string
for _, v := range a.core.multicast.interfaces() {
@ -609,6 +606,7 @@ func (a *admin) removePeer(p string) error {
}
// startTunWithMTU creates the tun/tap device, sets its address, and sets the MTU to the provided value.
/*
func (a *admin) startTunWithMTU(ifname string, iftapmode bool, ifmtu int) error {
// Close the TUN first if open
_ = a.core.router.tun.close()
@ -636,6 +634,7 @@ func (a *admin) startTunWithMTU(ifname string, iftapmode bool, ifmtu int) error
go a.core.router.tun.write()
return nil
}
*/
// getData_getSelf returns the self node's info for admin responses.
func (a *admin) getData_getSelf() *admin_nodeInfo {

View file

@ -55,25 +55,24 @@ func (c *cryptokey) init(core *Core) {
// Configure the CKR routes - this must only ever be called from the router
// goroutine, e.g. through router.doAdmin
func (c *cryptokey) configure() error {
c.core.configMutex.RLock()
defer c.core.configMutex.RUnlock()
current, _ := c.core.config.Get()
// Set enabled/disabled state
c.setEnabled(c.core.config.TunnelRouting.Enable)
c.setEnabled(current.TunnelRouting.Enable)
// Clear out existing routes
c.ipv6routes = make([]cryptokey_route, 0)
c.ipv4routes = make([]cryptokey_route, 0)
// Add IPv6 routes
for ipv6, pubkey := range c.core.config.TunnelRouting.IPv6Destinations {
for ipv6, pubkey := range current.TunnelRouting.IPv6Destinations {
if err := c.addRoute(ipv6, pubkey); err != nil {
return err
}
}
// Add IPv4 routes
for ipv4, pubkey := range c.core.config.TunnelRouting.IPv4Destinations {
for ipv4, pubkey := range current.TunnelRouting.IPv4Destinations {
if err := c.addRoute(ipv4, pubkey); err != nil {
return err
}
@ -85,7 +84,7 @@ func (c *cryptokey) configure() error {
// Add IPv6 sources
c.ipv6sources = make([]net.IPNet, 0)
for _, source := range c.core.config.TunnelRouting.IPv6Sources {
for _, source := range current.TunnelRouting.IPv6Sources {
if err := c.addSourceSubnet(source); err != nil {
return err
}
@ -93,7 +92,7 @@ func (c *cryptokey) configure() error {
// Add IPv4 sources
c.ipv4sources = make([]net.IPNet, 0)
for _, source := range c.core.config.TunnelRouting.IPv4Sources {
for _, source := range current.TunnelRouting.IPv4Sources {
if err := c.addSourceSubnet(source); err != nil {
return err
}

View file

@ -4,7 +4,6 @@ import (
"encoding/hex"
"io/ioutil"
"net"
"sync"
"time"
"github.com/gologme/log"
@ -29,9 +28,7 @@ type Core struct {
// This is the main data structure that holds everything else for a node
// We're going to keep our own copy of the provided config - that way we can
// guarantee that it will be covered by the mutex
config config.NodeConfig // Active config
configOld config.NodeConfig // Previous config
configMutex sync.RWMutex // Protects both config and configOld
config config.NodeState // Config
boxPub crypto.BoxPubKey
boxPriv crypto.BoxPrivKey
sigPub crypto.SigPubKey
@ -57,19 +54,21 @@ func (c *Core) init() error {
c.log = log.New(ioutil.Discard, "", 0)
}
boxPubHex, err := hex.DecodeString(c.config.EncryptionPublicKey)
current, _ := c.config.Get()
boxPubHex, err := hex.DecodeString(current.EncryptionPublicKey)
if err != nil {
return err
}
boxPrivHex, err := hex.DecodeString(c.config.EncryptionPrivateKey)
boxPrivHex, err := hex.DecodeString(current.EncryptionPrivateKey)
if err != nil {
return err
}
sigPubHex, err := hex.DecodeString(c.config.SigningPublicKey)
sigPubHex, err := hex.DecodeString(current.SigningPublicKey)
if err != nil {
return err
}
sigPrivHex, err := hex.DecodeString(c.config.SigningPrivateKey)
sigPrivHex, err := hex.DecodeString(current.SigningPrivateKey)
if err != nil {
return err
}
@ -97,19 +96,16 @@ func (c *Core) init() error {
func (c *Core) addPeerLoop() {
for {
// Get the peers from the config - these could change!
c.configMutex.RLock()
peers := c.config.Peers
interfacepeers := c.config.InterfacePeers
c.configMutex.RUnlock()
current, _ := c.config.Get()
// Add peers from the Peers section
for _, peer := range peers {
for _, peer := range current.Peers {
c.AddPeer(peer, "")
time.Sleep(time.Second)
}
// Add peers from the InterfacePeers section
for intf, intfpeers := range interfacepeers {
for intf, intfpeers := range current.InterfacePeers {
for _, peer := range intfpeers {
c.AddPeer(peer, intf)
time.Sleep(time.Second)
@ -126,10 +122,7 @@ func (c *Core) addPeerLoop() {
func (c *Core) UpdateConfig(config *config.NodeConfig) {
c.log.Infoln("Reloading configuration...")
c.configMutex.Lock()
c.configOld = c.config
c.config = *config
c.configMutex.Unlock()
c.config.Replace(*config)
errors := 0
@ -140,7 +133,7 @@ func (c *Core) UpdateConfig(config *config.NodeConfig) {
c.sessions.reconfigure,
c.peers.reconfigure,
c.router.reconfigure,
c.router.tun.reconfigure,
//c.router.tun.Reconfigure,
c.router.cryptokey.reconfigure,
c.switchTable.reconfigure,
c.link.reconfigure,
@ -181,13 +174,23 @@ func GetBuildVersion() string {
return buildVersion
}
// Starts up Yggdrasil using the provided NodeConfig, and outputs debug logging
// Set the router adapter
func (c *Core) SetRouterAdapter(adapter adapterImplementation) {
c.router.tun = adapter
}
// Starts up Yggdrasil using the provided NodeState, and outputs debug logging
// through the provided log.Logger. The started stack will include TCP and UDP
// sockets, a multicast discovery socket, an admin socket, router, switch and
// DHT node.
func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
c.log = log
c.config = config.NodeState{
Current: *nc,
Previous: *nc,
}
if name := GetBuildName(); name != "unknown" {
c.log.Infoln("Build name:", name)
}
@ -197,11 +200,6 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
c.log.Infoln("Starting up...")
c.configMutex.Lock()
c.config = *nc
c.configOld = c.config
c.configMutex.Unlock()
c.init()
if err := c.link.init(c); err != nil {
@ -209,9 +207,11 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
return err
}
if nc.SwitchOptions.MaxTotalQueueSize >= SwitchQueueTotalMinSize {
c.switchTable.queueTotalMaxSize = nc.SwitchOptions.MaxTotalQueueSize
c.config.Mutex.RLock()
if c.config.Current.SwitchOptions.MaxTotalQueueSize >= SwitchQueueTotalMinSize {
c.switchTable.queueTotalMaxSize = c.config.Current.SwitchOptions.MaxTotalQueueSize
}
c.config.Mutex.RUnlock()
if err := c.switchTable.start(); err != nil {
c.log.Errorln("Failed to start switch")
@ -233,7 +233,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
return err
}
if err := c.router.tun.start(); err != nil {
if err := c.router.tun.Start(c.router.addr, c.router.subnet); err != nil {
c.log.Errorln("Failed to start TUN/TAP")
return err
}
@ -247,7 +247,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
// Stops the Yggdrasil node.
func (c *Core) Stop() {
c.log.Infoln("Stopping...")
c.router.tun.close()
c.router.tun.Close()
c.admin.close()
}
@ -343,10 +343,12 @@ func (c *Core) GetTUNDefaultIfTAPMode() bool {
// Gets the current TUN/TAP interface name.
func (c *Core) GetTUNIfName() string {
return c.router.tun.iface.Name()
//return c.router.tun.iface.Name()
return c.router.tun.Name()
}
// Gets the current TUN/TAP interface MTU.
func (c *Core) GetTUNIfMTU() int {
return c.router.tun.mtu
//return c.router.tun.mtu
return c.router.tun.MTU()
}

View file

@ -1,331 +0,0 @@
package yggdrasil
// The ICMPv6 module implements functions to easily create ICMPv6
// packets. These functions, when mixed with the built-in Go IPv6
// and ICMP libraries, can be used to send control messages back
// to the host. Examples include:
// - NDP messages, when running in TAP mode
// - Packet Too Big messages, when packets exceed the session MTU
// - Destination Unreachable messages, when a session prohibits
// incoming traffic
import (
"encoding/binary"
"errors"
"net"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv6"
"github.com/yggdrasil-network/yggdrasil-go/src/address"
)
type macAddress [6]byte
const len_ETHER = 14
type icmpv6 struct {
tun *tunAdapter
mylladdr net.IP
mymac macAddress
peermacs map[address.Address]neighbor
}
type neighbor struct {
mac macAddress
learned bool
lastadvertisement time.Time
lastsolicitation time.Time
}
// Marshal returns the binary encoding of h.
func ipv6Header_Marshal(h *ipv6.Header) ([]byte, error) {
b := make([]byte, 40)
b[0] |= byte(h.Version) << 4
b[0] |= byte(h.TrafficClass) >> 4
b[1] |= byte(h.TrafficClass) << 4
b[1] |= byte(h.FlowLabel >> 16)
b[2] = byte(h.FlowLabel >> 8)
b[3] = byte(h.FlowLabel)
binary.BigEndian.PutUint16(b[4:6], uint16(h.PayloadLen))
b[6] = byte(h.NextHeader)
b[7] = byte(h.HopLimit)
copy(b[8:24], h.Src)
copy(b[24:40], h.Dst)
return b, nil
}
// Initialises the ICMPv6 module by assigning our link-local IPv6 address and
// our MAC address. ICMPv6 messages will always appear to originate from these
// addresses.
func (i *icmpv6) init(t *tunAdapter) {
i.tun = t
i.peermacs = make(map[address.Address]neighbor)
// Our MAC address and link-local address
i.mymac = macAddress{
0x02, 0x00, 0x00, 0x00, 0x00, 0x02}
i.mylladdr = net.IP{
0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFE}
copy(i.mymac[:], i.tun.core.router.addr[:])
copy(i.mylladdr[9:], i.tun.core.router.addr[1:])
}
// Parses an incoming ICMPv6 packet. The packet provided may be either an
// ethernet frame containing an IP packet, or the IP packet alone. This is
// determined by whether the TUN/TAP adapter is running in TUN (layer 3) or
// TAP (layer 2) mode.
func (i *icmpv6) parse_packet(datain []byte) {
var response []byte
var err error
// Parse the frame/packet
if i.tun.iface.IsTAP() {
response, err = i.parse_packet_tap(datain)
} else {
response, err = i.parse_packet_tun(datain, nil)
}
if err != nil {
return
}
// Write the packet to TUN/TAP
i.tun.iface.Write(response)
}
// Unwraps the ethernet headers of an incoming ICMPv6 packet and hands off
// the IP packet to the parse_packet_tun function for further processing.
// A response buffer is also created for the response message, also complete
// with ethernet headers.
func (i *icmpv6) parse_packet_tap(datain []byte) ([]byte, error) {
// Ignore non-IPv6 frames
if binary.BigEndian.Uint16(datain[12:14]) != uint16(0x86DD) {
return nil, nil
}
// Hand over to parse_packet_tun to interpret the IPv6 packet
mac := datain[6:12]
ipv6packet, err := i.parse_packet_tun(datain[len_ETHER:], &mac)
if err != nil {
return nil, err
}
// Create the response buffer
dataout := make([]byte, len_ETHER+ipv6.HeaderLen+32)
// Populate the response ethernet headers
copy(dataout[:6], datain[6:12])
copy(dataout[6:12], i.mymac[:])
binary.BigEndian.PutUint16(dataout[12:14], uint16(0x86DD))
// Copy the returned packet to our response ethernet frame
copy(dataout[len_ETHER:], ipv6packet)
return dataout, nil
}
// Unwraps the IP headers of an incoming IPv6 packet and performs various
// sanity checks on the packet - i.e. is the packet an ICMPv6 packet, does the
// ICMPv6 message match a known expected type. The relevant handler function
// is then called and a response packet may be returned.
func (i *icmpv6) parse_packet_tun(datain []byte, datamac *[]byte) ([]byte, error) {
// Parse the IPv6 packet headers
ipv6Header, err := ipv6.ParseHeader(datain[:ipv6.HeaderLen])
if err != nil {
return nil, err
}
// Check if the packet is IPv6
if ipv6Header.Version != ipv6.Version {
return nil, err
}
// Check if the packet is ICMPv6
if ipv6Header.NextHeader != 58 {
return nil, err
}
// Parse the ICMPv6 message contents
icmpv6Header, err := icmp.ParseMessage(58, datain[ipv6.HeaderLen:])
if err != nil {
return nil, err
}
// Check for a supported message type
switch icmpv6Header.Type {
case ipv6.ICMPTypeNeighborSolicitation:
if !i.tun.iface.IsTAP() {
return nil, errors.New("Ignoring Neighbor Solicitation in TUN mode")
}
response, err := i.handle_ndp(datain[ipv6.HeaderLen:])
if err == nil {
// Create our ICMPv6 response
responsePacket, err := i.create_icmpv6_tun(
ipv6Header.Src, i.mylladdr,
ipv6.ICMPTypeNeighborAdvertisement, 0,
&icmp.DefaultMessageBody{Data: response})
if err != nil {
return nil, err
}
// Send it back
return responsePacket, nil
} else {
return nil, err
}
case ipv6.ICMPTypeNeighborAdvertisement:
if !i.tun.iface.IsTAP() {
return nil, errors.New("Ignoring Neighbor Advertisement in TUN mode")
}
if datamac != nil {
var addr address.Address
var target address.Address
var mac macAddress
copy(addr[:], ipv6Header.Src[:])
copy(target[:], datain[48:64])
copy(mac[:], (*datamac)[:])
// i.tun.core.log.Printf("Learning peer MAC %x for %x\n", mac, target)
neighbor := i.peermacs[target]
neighbor.mac = mac
neighbor.learned = true
neighbor.lastadvertisement = time.Now()
i.peermacs[target] = neighbor
}
return nil, errors.New("No response needed")
}
return nil, errors.New("ICMPv6 type not matched")
}
// Creates an ICMPv6 packet based on the given icmp.MessageBody and other
// parameters, complete with ethernet and IP headers, which can be written
// directly to a TAP adapter.
func (i *icmpv6) create_icmpv6_tap(dstmac macAddress, dst net.IP, src net.IP, mtype ipv6.ICMPType, mcode int, mbody icmp.MessageBody) ([]byte, error) {
// Pass through to create_icmpv6_tun
ipv6packet, err := i.create_icmpv6_tun(dst, src, mtype, mcode, mbody)
if err != nil {
return nil, err
}
// Create the response buffer
dataout := make([]byte, len_ETHER+len(ipv6packet))
// Populate the response ethernet headers
copy(dataout[:6], dstmac[:6])
copy(dataout[6:12], i.mymac[:])
binary.BigEndian.PutUint16(dataout[12:14], uint16(0x86DD))
// Copy the returned packet to our response ethernet frame
copy(dataout[len_ETHER:], ipv6packet)
return dataout, nil
}
// Creates an ICMPv6 packet based on the given icmp.MessageBody and other
// parameters, complete with IP headers only, which can be written directly to
// a TUN adapter, or called directly by the create_icmpv6_tap function when
// generating a message for TAP adapters.
func (i *icmpv6) create_icmpv6_tun(dst net.IP, src net.IP, mtype ipv6.ICMPType, mcode int, mbody icmp.MessageBody) ([]byte, error) {
// Create the ICMPv6 message
icmpMessage := icmp.Message{
Type: mtype,
Code: mcode,
Body: mbody,
}
// Convert the ICMPv6 message into []byte
icmpMessageBuf, err := icmpMessage.Marshal(icmp.IPv6PseudoHeader(src, dst))
if err != nil {
return nil, err
}
// Create the IPv6 header
ipv6Header := ipv6.Header{
Version: ipv6.Version,
NextHeader: 58,
PayloadLen: len(icmpMessageBuf),
HopLimit: 255,
Src: src,
Dst: dst,
}
// Convert the IPv6 header into []byte
ipv6HeaderBuf, err := ipv6Header_Marshal(&ipv6Header)
if err != nil {
return nil, err
}
// Construct the packet
responsePacket := make([]byte, ipv6.HeaderLen+ipv6Header.PayloadLen)
copy(responsePacket[:ipv6.HeaderLen], ipv6HeaderBuf)
copy(responsePacket[ipv6.HeaderLen:], icmpMessageBuf)
// Send it back
return responsePacket, nil
}
func (i *icmpv6) create_ndp_tap(dst address.Address) ([]byte, error) {
// Create the ND payload
var payload [28]byte
copy(payload[:4], []byte{0x00, 0x00, 0x00, 0x00})
copy(payload[4:20], dst[:])
copy(payload[20:22], []byte{0x01, 0x01})
copy(payload[22:28], i.mymac[:6])
// Create the ICMPv6 solicited-node address
var dstaddr address.Address
copy(dstaddr[:13], []byte{
0xFF, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0xFF})
copy(dstaddr[13:], dst[13:16])
// Create the multicast MAC
var dstmac macAddress
copy(dstmac[:2], []byte{0x33, 0x33})
copy(dstmac[2:6], dstaddr[12:16])
// Create the ND request
requestPacket, err := i.create_icmpv6_tap(
dstmac, dstaddr[:], i.mylladdr,
ipv6.ICMPTypeNeighborSolicitation, 0,
&icmp.DefaultMessageBody{Data: payload[:]})
if err != nil {
return nil, err
}
neighbor := i.peermacs[dstaddr]
neighbor.lastsolicitation = time.Now()
i.peermacs[dstaddr] = neighbor
return requestPacket, nil
}
// Generates a response to an NDP discovery packet. This is effectively called
// when the host operating system generates an NDP request for any address in
// the fd00::/8 range, so that the operating system knows to route that traffic
// to the Yggdrasil TAP adapter.
func (i *icmpv6) handle_ndp(in []byte) ([]byte, error) {
// Ignore NDP requests for anything outside of fd00::/8
var source address.Address
copy(source[:], in[8:])
var snet address.Subnet
copy(snet[:], in[8:])
switch {
case source.IsValid():
case snet.IsValid():
default:
return nil, errors.New("Not an NDP for 0200::/7")
}
// Create our NDP message body response
body := make([]byte, 28)
binary.BigEndian.PutUint32(body[:4], uint32(0x20000000))
copy(body[4:20], in[8:24]) // Target address
body[20] = uint8(2)
body[21] = uint8(1)
copy(body[22:28], i.mymac[:6])
// Send it back
return body, nil
}

View file

@ -23,9 +23,8 @@ func (m *multicast) init(core *Core) {
m.core = core
m.reconfigure = make(chan chan error, 1)
m.listeners = make(map[string]*tcpListener)
m.core.configMutex.RLock()
m.listenPort = m.core.config.LinkLocalTCPPort
m.core.configMutex.RUnlock()
current, _ := m.core.config.Get()
m.listenPort = current.LinkLocalTCPPort
go func() {
for {
e := <-m.reconfigure
@ -70,9 +69,8 @@ func (m *multicast) start() error {
func (m *multicast) interfaces() map[string]net.Interface {
// Get interface expressions from config
m.core.configMutex.RLock()
exprs := m.core.config.MulticastInterfaces
m.core.configMutex.RUnlock()
current, _ := m.core.config.Get()
exprs := current.MulticastInterfaces
// Ask the system for network interfaces
interfaces := make(map[string]net.Interface)
allifaces, err := net.Interfaces()

View file

@ -44,42 +44,42 @@ func (ps *peers) init(c *Core) {
// because the key is in the whitelist or because the whitelist is empty.
func (ps *peers) isAllowedEncryptionPublicKey(box *crypto.BoxPubKey) bool {
boxstr := hex.EncodeToString(box[:])
ps.core.configMutex.RLock()
defer ps.core.configMutex.RUnlock()
for _, v := range ps.core.config.AllowedEncryptionPublicKeys {
ps.core.config.Mutex.RLock()
defer ps.core.config.Mutex.RUnlock()
for _, v := range ps.core.config.Current.AllowedEncryptionPublicKeys {
if v == boxstr {
return true
}
}
return len(ps.core.config.AllowedEncryptionPublicKeys) == 0
return len(ps.core.config.Current.AllowedEncryptionPublicKeys) == 0
}
// Adds a key to the whitelist.
func (ps *peers) addAllowedEncryptionPublicKey(box string) {
ps.core.configMutex.RLock()
defer ps.core.configMutex.RUnlock()
ps.core.config.AllowedEncryptionPublicKeys =
append(ps.core.config.AllowedEncryptionPublicKeys, box)
ps.core.config.Mutex.RLock()
defer ps.core.config.Mutex.RUnlock()
ps.core.config.Current.AllowedEncryptionPublicKeys =
append(ps.core.config.Current.AllowedEncryptionPublicKeys, box)
}
// Removes a key from the whitelist.
func (ps *peers) removeAllowedEncryptionPublicKey(box string) {
ps.core.configMutex.RLock()
defer ps.core.configMutex.RUnlock()
for k, v := range ps.core.config.AllowedEncryptionPublicKeys {
ps.core.config.Mutex.RLock()
defer ps.core.config.Mutex.RUnlock()
for k, v := range ps.core.config.Current.AllowedEncryptionPublicKeys {
if v == box {
ps.core.config.AllowedEncryptionPublicKeys =
append(ps.core.config.AllowedEncryptionPublicKeys[:k],
ps.core.config.AllowedEncryptionPublicKeys[k+1:]...)
ps.core.config.Current.AllowedEncryptionPublicKeys =
append(ps.core.config.Current.AllowedEncryptionPublicKeys[:k],
ps.core.config.Current.AllowedEncryptionPublicKeys[k+1:]...)
}
}
}
// Gets the whitelist of allowed keys for incoming connections.
func (ps *peers) getAllowedEncryptionPublicKeys() []string {
ps.core.configMutex.RLock()
defer ps.core.configMutex.RUnlock()
return ps.core.config.AllowedEncryptionPublicKeys
ps.core.config.Mutex.RLock()
defer ps.core.config.Mutex.RUnlock()
return ps.core.config.Current.AllowedEncryptionPublicKeys
}
// Atomically gets a map[switchPort]*peer of known peers.

View file

@ -26,9 +26,6 @@ import (
"bytes"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv6"
"github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
"github.com/yggdrasil-network/yggdrasil-go/src/util"
@ -44,8 +41,7 @@ type router struct {
in <-chan []byte // packets we received from the network, link to peer's "out"
out func([]byte) // packets we're sending to the network, link to peer's "in"
toRecv chan router_recvPacket // packets to handle via recvPacket()
tun tunAdapter // TUN/TAP adapter
adapters []Adapter // Other adapters
tun adapterImplementation // TUN/TAP adapter
recv chan<- []byte // place where the tun pulls received packets from
send <-chan []byte // place where the tun puts outgoing packets
reset chan struct{} // signal that coords changed (re-init sessions/dht)
@ -112,11 +108,11 @@ func (r *router) init(core *Core) {
r.reset = make(chan struct{}, 1)
r.admin = make(chan func(), 32)
r.nodeinfo.init(r.core)
r.core.configMutex.RLock()
r.nodeinfo.setNodeInfo(r.core.config.NodeInfo, r.core.config.NodeInfoPrivacy)
r.core.configMutex.RUnlock()
r.core.config.Mutex.RLock()
r.nodeinfo.setNodeInfo(r.core.config.Current.NodeInfo, r.core.config.Current.NodeInfoPrivacy)
r.core.config.Mutex.RUnlock()
r.cryptokey.init(r.core)
r.tun.init(r.core, send, recv)
r.tun.Init(&r.core.config, r.core.log, send, recv)
}
// Starts the mainLoop goroutine.
@ -157,9 +153,8 @@ func (r *router) mainLoop() {
case f := <-r.admin:
f()
case e := <-r.reconfigure:
r.core.configMutex.RLock()
e <- r.nodeinfo.setNodeInfo(r.core.config.NodeInfo, r.core.config.NodeInfoPrivacy)
r.core.configMutex.RUnlock()
current, _ := r.core.config.Get()
e <- r.nodeinfo.setNodeInfo(current.NodeInfo, current.NodeInfoPrivacy)
}
}
}
@ -308,7 +303,7 @@ func (r *router) sendPacket(bs []byte) {
// Generate an ICMPv6 Packet Too Big for packets larger than session MTU
if len(bs) > int(sinfo.getMTU()) {
// Get the size of the oversized payload, up to a max of 900 bytes
window := 900
/*window := 900
if int(sinfo.getMTU()) < window {
window = int(sinfo.getMTU())
}
@ -320,12 +315,12 @@ func (r *router) sendPacket(bs []byte) {
}
// Create the ICMPv6 response from it
icmpv6Buf, err := r.tun.icmpv6.create_icmpv6_tun(
icmpv6Buf, err := CreateICMPv6(
bs[8:24], bs[24:40],
ipv6.ICMPTypePacketTooBig, 0, ptb)
if err == nil {
r.recv <- icmpv6Buf
}
}*/
// Don't continue - drop the packet
return

View file

@ -148,17 +148,17 @@ func (ss *sessions) init(core *Core) {
// Determines whether the session firewall is enabled.
func (ss *sessions) isSessionFirewallEnabled() bool {
ss.core.configMutex.RLock()
defer ss.core.configMutex.RUnlock()
ss.core.config.Mutex.RLock()
defer ss.core.config.Mutex.RUnlock()
return ss.core.config.SessionFirewall.Enable
return ss.core.config.Current.SessionFirewall.Enable
}
// Determines whether the session with a given publickey is allowed based on
// session firewall rules.
func (ss *sessions) isSessionAllowed(pubkey *crypto.BoxPubKey, initiator bool) bool {
ss.core.configMutex.RLock()
defer ss.core.configMutex.RUnlock()
ss.core.config.Mutex.RLock()
defer ss.core.config.Mutex.RUnlock()
// Allow by default if the session firewall is disabled
if !ss.isSessionFirewallEnabled() {
@ -167,7 +167,7 @@ func (ss *sessions) isSessionAllowed(pubkey *crypto.BoxPubKey, initiator bool) b
// Prepare for checking whitelist/blacklist
var box crypto.BoxPubKey
// Reject blacklisted nodes
for _, b := range ss.core.config.SessionFirewall.BlacklistEncryptionPublicKeys {
for _, b := range ss.core.config.Current.SessionFirewall.BlacklistEncryptionPublicKeys {
key, err := hex.DecodeString(b)
if err == nil {
copy(box[:crypto.BoxPubKeyLen], key)
@ -177,7 +177,7 @@ func (ss *sessions) isSessionAllowed(pubkey *crypto.BoxPubKey, initiator bool) b
}
}
// Allow whitelisted nodes
for _, b := range ss.core.config.SessionFirewall.WhitelistEncryptionPublicKeys {
for _, b := range ss.core.config.Current.SessionFirewall.WhitelistEncryptionPublicKeys {
key, err := hex.DecodeString(b)
if err == nil {
copy(box[:crypto.BoxPubKeyLen], key)
@ -187,7 +187,7 @@ func (ss *sessions) isSessionAllowed(pubkey *crypto.BoxPubKey, initiator bool) b
}
}
// Allow outbound sessions if appropriate
if ss.core.config.SessionFirewall.AlwaysAllowOutbound {
if ss.core.config.Current.SessionFirewall.AlwaysAllowOutbound {
if initiator {
return true
}
@ -201,11 +201,11 @@ func (ss *sessions) isSessionAllowed(pubkey *crypto.BoxPubKey, initiator bool) b
}
}
// Allow direct peers if appropriate
if ss.core.config.SessionFirewall.AllowFromDirect && isDirectPeer {
if ss.core.config.Current.SessionFirewall.AllowFromDirect && isDirectPeer {
return true
}
// Allow remote nodes if appropriate
if ss.core.config.SessionFirewall.AllowFromRemote && !isDirectPeer {
if ss.core.config.Current.SessionFirewall.AllowFromRemote && !isDirectPeer {
return true
}
// Finally, default-deny if not matching any of the above rules
@ -277,7 +277,7 @@ func (ss *sessions) createSession(theirPermKey *crypto.BoxPubKey) *sessionInfo {
sinfo.mySesPriv = *priv
sinfo.myNonce = *crypto.NewBoxNonce()
sinfo.theirMTU = 1280
sinfo.myMTU = uint16(ss.core.router.tun.mtu)
sinfo.myMTU = uint16(ss.core.router.tun.MTU())
now := time.Now()
sinfo.time = now
sinfo.mtuTime = now

View file

@ -188,9 +188,7 @@ func (t *switchTable) init(core *Core) {
now := time.Now()
t.core = core
t.reconfigure = make(chan chan error, 1)
t.core.configMutex.RLock()
t.key = t.core.sigPub
t.core.configMutex.RUnlock()
locator := switchLocator{root: t.key, tstamp: now.Unix()}
peers := make(map[switchPort]peerInfo)
t.data = switchData{locator: locator, peers: peers}

View file

@ -82,10 +82,10 @@ func (t *tcp) init(l *link) error {
go func() {
for {
e := <-t.reconfigure
t.link.core.configMutex.RLock()
added := util.Difference(t.link.core.config.Listen, t.link.core.configOld.Listen)
deleted := util.Difference(t.link.core.configOld.Listen, t.link.core.config.Listen)
t.link.core.configMutex.RUnlock()
t.link.core.config.Mutex.RLock()
added := util.Difference(t.link.core.config.Current.Listen, t.link.core.config.Previous.Listen)
deleted := util.Difference(t.link.core.config.Previous.Listen, t.link.core.config.Current.Listen)
t.link.core.config.Mutex.RUnlock()
if len(added) > 0 || len(deleted) > 0 {
for _, a := range added {
if a[:6] != "tcp://" {
@ -115,9 +115,9 @@ func (t *tcp) init(l *link) error {
}
}()
t.link.core.configMutex.RLock()
defer t.link.core.configMutex.RUnlock()
for _, listenaddr := range t.link.core.config.Listen {
t.link.core.config.Mutex.RLock()
defer t.link.core.config.Mutex.RUnlock()
for _, listenaddr := range t.link.core.config.Current.Listen {
if listenaddr[:6] != "tcp://" {
continue
}

View file

@ -1,266 +0,0 @@
package yggdrasil
// This manages the tun driver to send/recv packets to/from applications
import (
"bytes"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/songgao/packets/ethernet"
"github.com/yggdrasil-network/water"
"github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/defaults"
"github.com/yggdrasil-network/yggdrasil-go/src/util"
)
const tun_IPv6_HEADER_LENGTH = 40
const tun_ETHER_HEADER_LENGTH = 14
// Represents a running TUN/TAP interface.
type tunAdapter struct {
Adapter
icmpv6 icmpv6
mtu int
iface *water.Interface
mutex sync.RWMutex // Protects the below
isOpen bool
}
// Gets the maximum supported MTU for the platform based on the defaults in
// defaults.GetDefaults().
func getSupportedMTU(mtu int) int {
if mtu > defaults.GetDefaults().MaximumIfMTU {
return defaults.GetDefaults().MaximumIfMTU
}
return mtu
}
// Initialises the TUN/TAP adapter.
func (tun *tunAdapter) init(core *Core, send chan<- []byte, recv <-chan []byte) {
tun.Adapter.init(core, send, recv)
tun.icmpv6.init(tun)
go func() {
for {
e := <-tun.reconfigure
tun.core.configMutex.RLock()
updated := tun.core.config.IfName != tun.core.configOld.IfName ||
tun.core.config.IfTAPMode != tun.core.configOld.IfTAPMode ||
tun.core.config.IfMTU != tun.core.configOld.IfMTU
tun.core.configMutex.RUnlock()
if updated {
tun.core.log.Warnln("Reconfiguring TUN/TAP is not supported yet")
e <- nil
} else {
e <- nil
}
}
}()
}
// Starts the setup process for the TUN/TAP adapter, and if successful, starts
// the read/write goroutines to handle packets on that interface.
func (tun *tunAdapter) start() error {
tun.core.configMutex.RLock()
ifname := tun.core.config.IfName
iftapmode := tun.core.config.IfTAPMode
addr := fmt.Sprintf("%s/%d", net.IP(tun.core.router.addr[:]).String(), 8*len(address.GetPrefix())-1)
mtu := tun.core.config.IfMTU
tun.core.configMutex.RUnlock()
if ifname != "none" {
if err := tun.setup(ifname, iftapmode, addr, mtu); err != nil {
return err
}
}
if ifname == "none" || ifname == "dummy" {
return nil
}
tun.mutex.Lock()
tun.isOpen = true
tun.mutex.Unlock()
go func() { tun.core.log.Errorln("WARNING: tun.read() exited with error:", tun.read()) }()
go func() { tun.core.log.Errorln("WARNING: tun.write() exited with error:", tun.write()) }()
if iftapmode {
go func() {
for {
if _, ok := tun.icmpv6.peermacs[tun.core.router.addr]; ok {
break
}
request, err := tun.icmpv6.create_ndp_tap(tun.core.router.addr)
if err != nil {
panic(err)
}
if _, err := tun.iface.Write(request); err != nil {
panic(err)
}
time.Sleep(time.Second)
}
}()
}
return nil
}
// Writes a packet to the TUN/TAP adapter. If the adapter is running in TAP
// mode then additional ethernet encapsulation is added for the benefit of the
// host operating system.
func (tun *tunAdapter) write() error {
for {
data := <-tun.recv
if tun.iface == nil {
continue
}
if tun.iface.IsTAP() {
var destAddr address.Address
if data[0]&0xf0 == 0x60 {
if len(data) < 40 {
panic("Tried to send a packet shorter than an IPv6 header...")
}
copy(destAddr[:16], data[24:])
} else if data[0]&0xf0 == 0x40 {
if len(data) < 20 {
panic("Tried to send a packet shorter than an IPv4 header...")
}
copy(destAddr[:4], data[16:])
} else {
return errors.New("Invalid address family")
}
sendndp := func(destAddr address.Address) {
neigh, known := tun.icmpv6.peermacs[destAddr]
known = known && (time.Since(neigh.lastsolicitation).Seconds() < 30)
if !known {
request, err := tun.icmpv6.create_ndp_tap(destAddr)
if err != nil {
panic(err)
}
if _, err := tun.iface.Write(request); err != nil {
panic(err)
}
tun.icmpv6.peermacs[destAddr] = neighbor{
lastsolicitation: time.Now(),
}
}
}
var peermac macAddress
var peerknown bool
if data[0]&0xf0 == 0x40 {
destAddr = tun.core.router.addr
} else if data[0]&0xf0 == 0x60 {
if !bytes.Equal(tun.core.router.addr[:16], destAddr[:16]) && !bytes.Equal(tun.core.router.subnet[:8], destAddr[:8]) {
destAddr = tun.core.router.addr
}
}
if neighbor, ok := tun.icmpv6.peermacs[destAddr]; ok && neighbor.learned {
peermac = neighbor.mac
peerknown = true
} else if neighbor, ok := tun.icmpv6.peermacs[tun.core.router.addr]; ok && neighbor.learned {
peermac = neighbor.mac
peerknown = true
sendndp(destAddr)
} else {
sendndp(tun.core.router.addr)
}
if peerknown {
var proto ethernet.Ethertype
switch {
case data[0]&0xf0 == 0x60:
proto = ethernet.IPv6
case data[0]&0xf0 == 0x40:
proto = ethernet.IPv4
}
var frame ethernet.Frame
frame.Prepare(
peermac[:6], // Destination MAC address
tun.icmpv6.mymac[:6], // Source MAC address
ethernet.NotTagged, // VLAN tagging
proto, // Ethertype
len(data)) // Payload length
copy(frame[tun_ETHER_HEADER_LENGTH:], data[:])
if _, err := tun.iface.Write(frame); err != nil {
tun.mutex.RLock()
open := tun.isOpen
tun.mutex.RUnlock()
if !open {
return nil
} else {
panic(err)
}
}
}
} else {
if _, err := tun.iface.Write(data); err != nil {
tun.mutex.RLock()
open := tun.isOpen
tun.mutex.RUnlock()
if !open {
return nil
} else {
panic(err)
}
}
}
util.PutBytes(data)
}
}
// Reads any packets that are waiting on the TUN/TAP adapter. If the adapter
// is running in TAP mode then the ethernet headers will automatically be
// processed and stripped if necessary. If an ICMPv6 packet is found, then
// the relevant helper functions in icmpv6.go are called.
func (tun *tunAdapter) read() error {
mtu := tun.mtu
if tun.iface.IsTAP() {
mtu += tun_ETHER_HEADER_LENGTH
}
buf := make([]byte, mtu)
for {
n, err := tun.iface.Read(buf)
if err != nil {
tun.mutex.RLock()
open := tun.isOpen
tun.mutex.RUnlock()
if !open {
return nil
} else {
// panic(err)
return err
}
}
o := 0
if tun.iface.IsTAP() {
o = tun_ETHER_HEADER_LENGTH
}
switch {
case buf[o]&0xf0 == 0x60 && n == 256*int(buf[o+4])+int(buf[o+5])+tun_IPv6_HEADER_LENGTH+o:
case buf[o]&0xf0 == 0x40 && n == 256*int(buf[o+2])+int(buf[o+3])+o:
default:
continue
}
if buf[o+6] == 58 {
if tun.iface.IsTAP() {
// Found an ICMPv6 packet
b := make([]byte, n)
copy(b, buf)
go tun.icmpv6.parse_packet(b)
}
}
packet := append(util.GetBytes(), buf[o:n]...)
tun.send <- packet
}
}
// Closes the TUN/TAP adapter. This is only usually called when the Yggdrasil
// process stops. Typically this operation will happen quickly, but on macOS
// it can block until a read operation is completed.
func (tun *tunAdapter) close() error {
tun.mutex.Lock()
tun.isOpen = false
tun.mutex.Unlock()
if tun.iface == nil {
return nil
}
return tun.iface.Close()
}

View file

@ -1,171 +0,0 @@
// +build openbsd freebsd netbsd
package yggdrasil
import (
"encoding/binary"
"os/exec"
"strconv"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/unix"
"github.com/yggdrasil-network/water"
)
const SIOCSIFADDR_IN6 = (0x80000000) | ((288 & 0x1fff) << 16) | uint32(byte('i'))<<8 | 12
type in6_addrlifetime struct {
ia6t_expire float64
ia6t_preferred float64
ia6t_vltime uint32
ia6t_pltime uint32
}
type sockaddr_in6 struct {
sin6_len uint8
sin6_family uint8
sin6_port uint8
sin6_flowinfo uint32
sin6_addr [8]uint16
sin6_scope_id uint32
}
/*
from <netinet6/in6_var.h>
struct in6_ifreq {
277 char ifr_name[IFNAMSIZ];
278 union {
279 struct sockaddr_in6 ifru_addr;
280 struct sockaddr_in6 ifru_dstaddr;
281 int ifru_flags;
282 int ifru_flags6;
283 int ifru_metric;
284 caddr_t ifru_data;
285 struct in6_addrlifetime ifru_lifetime;
286 struct in6_ifstat ifru_stat;
287 struct icmp6_ifstat ifru_icmp6stat;
288 u_int32_t ifru_scope_id[16];
289 } ifr_ifru;
290 };
*/
type in6_ifreq_mtu struct {
ifr_name [syscall.IFNAMSIZ]byte
ifru_mtu int
}
type in6_ifreq_addr struct {
ifr_name [syscall.IFNAMSIZ]byte
ifru_addr sockaddr_in6
}
type in6_ifreq_flags struct {
ifr_name [syscall.IFNAMSIZ]byte
flags int
}
type in6_ifreq_lifetime struct {
ifr_name [syscall.IFNAMSIZ]byte
ifru_addrlifetime in6_addrlifetime
}
// Sets the IPv6 address of the utun adapter. On all BSD platforms (FreeBSD,
// OpenBSD, NetBSD) an attempt is made to set the adapter properties by using
// a system socket and making syscalls to the kernel. This is not refined though
// and often doesn't work (if at all), therefore if a call fails, it resorts
// to calling "ifconfig" instead.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
var config water.Config
if ifname[:4] == "auto" {
ifname = "/dev/tap0"
}
if len(ifname) < 9 {
panic("TUN/TAP name must be in format /dev/tunX or /dev/tapX")
}
switch {
case iftapmode || ifname[:8] == "/dev/tap":
config = water.Config{DeviceType: water.TAP}
case !iftapmode || ifname[:8] == "/dev/tun":
panic("TUN mode is not currently supported on this platform, please use TAP instead")
default:
panic("TUN/TAP name must be in format /dev/tunX or /dev/tapX")
}
config.Name = ifname
iface, err := water.New(config)
if err != nil {
panic(err)
}
tun.iface = iface
tun.mtu = getSupportedMTU(mtu)
return tun.setupAddress(addr)
}
func (tun *tunAdapter) setupAddress(addr string) error {
var sfd int
var err error
// Create system socket
if sfd, err = unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, 0); err != nil {
tun.core.log.Printf("Create AF_INET socket failed: %v.", err)
return err
}
// Friendly output
tun.core.log.Infof("Interface name: %s", tun.iface.Name())
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", tun.mtu)
// Create the MTU request
var ir in6_ifreq_mtu
copy(ir.ifr_name[:], tun.iface.Name())
ir.ifru_mtu = int(tun.mtu)
// Set the MTU
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(sfd), uintptr(syscall.SIOCSIFMTU), uintptr(unsafe.Pointer(&ir))); errno != 0 {
err = errno
tun.core.log.Errorf("Error in SIOCSIFMTU: %v", errno)
// Fall back to ifconfig to set the MTU
cmd := exec.Command("ifconfig", tun.iface.Name(), "mtu", string(tun.mtu))
tun.core.log.Warnf("Using ifconfig as fallback: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Errorf("SIOCSIFMTU fallback failed: %v.", err)
tun.core.log.Traceln(string(output))
}
}
// Create the address request
// FIXME: I don't work!
var ar in6_ifreq_addr
copy(ar.ifr_name[:], tun.iface.Name())
ar.ifru_addr.sin6_len = uint8(unsafe.Sizeof(ar.ifru_addr))
ar.ifru_addr.sin6_family = unix.AF_INET6
parts := strings.Split(strings.Split(addr, "/")[0], ":")
for i := 0; i < 8; i++ {
addr, _ := strconv.ParseUint(parts[i], 16, 16)
b := make([]byte, 16)
binary.LittleEndian.PutUint16(b, uint16(addr))
ar.ifru_addr.sin6_addr[i] = uint16(binary.BigEndian.Uint16(b))
}
// Set the interface address
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(sfd), uintptr(SIOCSIFADDR_IN6), uintptr(unsafe.Pointer(&ar))); errno != 0 {
err = errno
tun.core.log.Errorf("Error in SIOCSIFADDR_IN6: %v", errno)
// Fall back to ifconfig to set the address
cmd := exec.Command("ifconfig", tun.iface.Name(), "inet6", addr)
tun.core.log.Warnf("Using ifconfig as fallback: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Errorf("SIOCSIFADDR_IN6 fallback failed: %v.", err)
tun.core.log.Traceln(string(output))
}
}
return nil
}

View file

@ -1,118 +0,0 @@
// +build !mobile
package yggdrasil
// The darwin platform specific tun parts
import (
"encoding/binary"
"strconv"
"strings"
"unsafe"
"golang.org/x/sys/unix"
water "github.com/yggdrasil-network/water"
)
// Configures the "utun" adapter with the correct IPv6 address and MTU.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
if iftapmode {
tun.core.log.Warnln("TAP mode is not supported on this platform, defaulting to TUN")
}
config := water.Config{DeviceType: water.TUN}
iface, err := water.New(config)
if err != nil {
panic(err)
}
tun.iface = iface
tun.mtu = getSupportedMTU(mtu)
return tun.setupAddress(addr)
}
const darwin_SIOCAIFADDR_IN6 = 2155899162
type in6_addrlifetime struct {
ia6t_expire float64
ia6t_preferred float64
ia6t_vltime uint32
ia6t_pltime uint32
}
type sockaddr_in6 struct {
sin6_len uint8
sin6_family uint8
sin6_port uint8
sin6_flowinfo uint32
sin6_addr [8]uint16
sin6_scope_id uint32
}
type in6_aliasreq struct {
ifra_name [16]byte
ifra_addr sockaddr_in6
ifra_dstaddr sockaddr_in6
ifra_prefixmask sockaddr_in6
ifra_flags uint32
ifra_lifetime in6_addrlifetime
}
type ifreq struct {
ifr_name [16]byte
ifru_mtu uint32
}
// Sets the IPv6 address of the utun adapter. On Darwin/macOS this is done using
// a system socket and making direct syscalls to the kernel.
func (tun *tunAdapter) setupAddress(addr string) error {
var fd int
var err error
if fd, err = unix.Socket(unix.AF_INET6, unix.SOCK_DGRAM, 0); err != nil {
tun.core.log.Printf("Create AF_SYSTEM socket failed: %v.", err)
return err
}
var ar in6_aliasreq
copy(ar.ifra_name[:], tun.iface.Name())
ar.ifra_prefixmask.sin6_len = uint8(unsafe.Sizeof(ar.ifra_prefixmask))
b := make([]byte, 16)
binary.LittleEndian.PutUint16(b, uint16(0xFE00))
ar.ifra_prefixmask.sin6_addr[0] = uint16(binary.BigEndian.Uint16(b))
ar.ifra_addr.sin6_len = uint8(unsafe.Sizeof(ar.ifra_addr))
ar.ifra_addr.sin6_family = unix.AF_INET6
parts := strings.Split(strings.Split(addr, "/")[0], ":")
for i := 0; i < 8; i++ {
addr, _ := strconv.ParseUint(parts[i], 16, 16)
b := make([]byte, 16)
binary.LittleEndian.PutUint16(b, uint16(addr))
ar.ifra_addr.sin6_addr[i] = uint16(binary.BigEndian.Uint16(b))
}
ar.ifra_lifetime.ia6t_vltime = 0xFFFFFFFF
ar.ifra_lifetime.ia6t_pltime = 0xFFFFFFFF
var ir ifreq
copy(ir.ifr_name[:], tun.iface.Name())
ir.ifru_mtu = uint32(tun.mtu)
tun.core.log.Infof("Interface name: %s", ar.ifra_name)
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", ir.ifru_mtu)
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(darwin_SIOCAIFADDR_IN6), uintptr(unsafe.Pointer(&ar))); errno != 0 {
err = errno
tun.core.log.Errorf("Error in darwin_SIOCAIFADDR_IN6: %v", errno)
return err
}
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(unix.SIOCSIFMTU), uintptr(unsafe.Pointer(&ir))); errno != 0 {
err = errno
tun.core.log.Errorf("Error in SIOCSIFMTU: %v", errno)
return err
}
return err
}

View file

@ -1,19 +0,0 @@
// +build mobile
package yggdrasil
// This is to catch unsupported platforms
// If your platform supports tun devices, you could try configuring it manually
// Creates the TUN/TAP adapter, if supported by the Water library. Note that
// no guarantees are made at this point on an unsupported platform.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
tun.mtu = getSupportedMTU(mtu)
return tun.setupAddress(addr)
}
// We don't know how to set the IPv6 address on an unknown platform, therefore
// write about it to stdout and don't try to do anything further.
func (tun *tunAdapter) setupAddress(addr string) error {
return nil
}

View file

@ -1,86 +0,0 @@
// +build !mobile
package yggdrasil
// The linux platform specific tun parts
import (
"errors"
"fmt"
"net"
"github.com/docker/libcontainer/netlink"
water "github.com/yggdrasil-network/water"
)
// Configures the TAP adapter with the correct IPv6 address and MTU.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
var config water.Config
if iftapmode {
config = water.Config{DeviceType: water.TAP}
} else {
config = water.Config{DeviceType: water.TUN}
}
if ifname != "" && ifname != "auto" {
config.Name = ifname
}
iface, err := water.New(config)
if err != nil {
panic(err)
}
tun.iface = iface
tun.mtu = getSupportedMTU(mtu)
// The following check is specific to Linux, as the TAP driver only supports
// an MTU of 65535-14 to make room for the ethernet headers. This makes sure
// that the MTU gets rounded down to 65521 instead of causing a panic.
if iftapmode {
if tun.mtu > 65535-tun_ETHER_HEADER_LENGTH {
tun.mtu = 65535 - tun_ETHER_HEADER_LENGTH
}
}
// Friendly output
tun.core.log.Infof("Interface name: %s", tun.iface.Name())
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", tun.mtu)
return tun.setupAddress(addr)
}
// Configures the TAP adapter with the correct IPv6 address and MTU. Netlink
// is used to do this, so there is not a hard requirement on "ip" or "ifconfig"
// to exist on the system, but this will fail if Netlink is not present in the
// kernel (it nearly always is).
func (tun *tunAdapter) setupAddress(addr string) error {
// Set address
var netIF *net.Interface
ifces, err := net.Interfaces()
if err != nil {
return err
}
for _, ifce := range ifces {
if ifce.Name == tun.iface.Name() {
var newIF = ifce
netIF = &newIF // Don't point inside ifces, it's apparently unsafe?...
}
}
if netIF == nil {
return errors.New(fmt.Sprintf("Failed to find interface: %s", tun.iface.Name()))
}
ip, ipNet, err := net.ParseCIDR(addr)
if err != nil {
return err
}
err = netlink.NetworkLinkAddIp(netIF, ip, ipNet)
if err != nil {
return err
}
err = netlink.NetworkSetMTU(netIF, tun.mtu)
if err != nil {
return err
}
netlink.NetworkLinkUp(netIF)
if err != nil {
return err
}
return nil
}

View file

@ -1,33 +0,0 @@
// +build !linux,!darwin,!windows,!openbsd,!freebsd,!netbsd,!mobile
package yggdrasil
import water "github.com/yggdrasil-network/water"
// This is to catch unsupported platforms
// If your platform supports tun devices, you could try configuring it manually
// Creates the TUN/TAP adapter, if supported by the Water library. Note that
// no guarantees are made at this point on an unsupported platform.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
var config water.Config
if iftapmode {
config = water.Config{DeviceType: water.TAP}
} else {
config = water.Config{DeviceType: water.TUN}
}
iface, err := water.New(config)
if err != nil {
panic(err)
}
tun.iface = iface
tun.mtu = getSupportedMTU(mtu)
return tun.setupAddress(addr)
}
// We don't know how to set the IPv6 address on an unknown platform, therefore
// write about it to stdout and don't try to do anything further.
func (tun *tunAdapter) setupAddress(addr string) error {
tun.core.log.Warnln("Platform not supported, you must set the address of", tun.iface.Name(), "to", addr)
return nil
}

View file

@ -1,99 +0,0 @@
package yggdrasil
import (
"fmt"
"os/exec"
"strings"
water "github.com/yggdrasil-network/water"
)
// This is to catch Windows platforms
// Configures the TAP adapter with the correct IPv6 address and MTU. On Windows
// we don't make use of a direct operating system API to do this - we instead
// delegate the hard work to "netsh".
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
if !iftapmode {
tun.core.log.Warnln("TUN mode is not supported on this platform, defaulting to TAP")
}
config := water.Config{DeviceType: water.TAP}
config.PlatformSpecificParams.ComponentID = "tap0901"
config.PlatformSpecificParams.Network = "169.254.0.1/32"
if ifname == "auto" {
config.PlatformSpecificParams.InterfaceName = ""
} else {
config.PlatformSpecificParams.InterfaceName = ifname
}
iface, err := water.New(config)
if err != nil {
panic(err)
}
// Disable/enable the interface to resets its configuration (invalidating iface)
cmd := exec.Command("netsh", "interface", "set", "interface", iface.Name(), "admin=DISABLED")
tun.core.log.Printf("netsh command: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
cmd = exec.Command("netsh", "interface", "set", "interface", iface.Name(), "admin=ENABLED")
tun.core.log.Printf("netsh command: %v", strings.Join(cmd.Args, " "))
output, err = cmd.CombinedOutput()
if err != nil {
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
// Get a new iface
iface, err = water.New(config)
if err != nil {
panic(err)
}
tun.iface = iface
tun.mtu = getSupportedMTU(mtu)
err = tun.setupMTU(tun.mtu)
if err != nil {
panic(err)
}
// Friendly output
tun.core.log.Infof("Interface name: %s", tun.iface.Name())
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", tun.mtu)
return tun.setupAddress(addr)
}
// Sets the MTU of the TAP adapter.
func (tun *tunAdapter) setupMTU(mtu int) error {
// Set MTU
cmd := exec.Command("netsh", "interface", "ipv6", "set", "subinterface",
fmt.Sprintf("interface=%s", tun.iface.Name()),
fmt.Sprintf("mtu=%d", mtu),
"store=active")
tun.core.log.Debugln("netsh command: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
return nil
}
// Sets the IPv6 address of the TAP adapter.
func (tun *tunAdapter) setupAddress(addr string) error {
// Set address
cmd := exec.Command("netsh", "interface", "ipv6", "add", "address",
fmt.Sprintf("interface=%s", tun.iface.Name()),
fmt.Sprintf("addr=%s", addr),
"store=active")
tun.core.log.Debugln("netsh command: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
return nil
}