Break out TUN/TAP into another package, make various other changes to support it

This commit is contained in:
Neil Alexander 2019-03-27 20:10:25 +00:00
parent 67c670ab4c
commit 7f0e3d5135
No known key found for this signature in database
GPG key ID: A02A2019A2BB0944
22 changed files with 247 additions and 204 deletions

26
src/adapter/adapter.go Normal file
View file

@ -0,0 +1,26 @@
package adapter
import (
"github.com/gologme/log"
"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)
type Adapter struct {
Config *config.StatefulNodeConfig
Log *log.Logger
Send chan<- []byte
Recv <-chan []byte
Reconfigure chan chan error
}
// Initialises the adapter.
func (adapter *Adapter) Init(config *config.StatefulNodeConfig, log *log.Logger, send chan<- []byte, recv <-chan []byte) {
adapter.Config = config
adapter.Log = log
adapter.Send = send
adapter.Recv = recv
adapter.Reconfigure = make(chan chan error, 1)
}

View file

@ -2,11 +2,30 @@ package config
import ( import (
"encoding/hex" "encoding/hex"
"sync"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto" "github.com/yggdrasil-network/yggdrasil-go/src/crypto"
"github.com/yggdrasil-network/yggdrasil-go/src/defaults" "github.com/yggdrasil-network/yggdrasil-go/src/defaults"
) )
// A configuration item that represents the current configuration and the
// previous configuration, protected by a mutex. Having this removes a ref to
// Core
type StatefulNodeConfig struct {
Current NodeConfig
Previous NodeConfig
Mutex sync.RWMutex
}
// Replace updates the active node configuration and stores the previous
// config so that we can delta it if needed
func (snc *StatefulNodeConfig) Replace(new NodeConfig) {
snc.Mutex.Lock()
snc.Previous = snc.Current
snc.Current = new
snc.Mutex.Unlock()
}
// NodeConfig defines all configuration values needed to run a signle yggdrasil node // NodeConfig defines all configuration values needed to run a signle yggdrasil node
type NodeConfig struct { type NodeConfig struct {
Peers []string `comment:"List of connection strings for outbound peer connections in URI format,\ne.g. tcp://a.b.c.d:e or socks://a.b.c.d:e/f.g.h.i:j. These connections\nwill obey the operating system routing table, therefore you should\nuse this section when you may connect via different interfaces."` Peers []string `comment:"List of connection strings for outbound peer connections in URI format,\ne.g. tcp://a.b.c.d:e or socks://a.b.c.d:e/f.g.h.i:j. These connections\nwill obey the operating system routing table, therefore you should\nuse this section when you may connect via different interfaces."`

View file

@ -1,4 +1,4 @@
package yggdrasil package tuntap
// The ICMPv6 module implements functions to easily create ICMPv6 // The ICMPv6 module implements functions to easily create ICMPv6
// packets. These functions, when mixed with the built-in Go IPv6 // packets. These functions, when mixed with the built-in Go IPv6
@ -26,7 +26,7 @@ type macAddress [6]byte
const len_ETHER = 14 const len_ETHER = 14
type icmpv6 struct { type icmpv6 struct {
tun *tunAdapter tun *TunAdapter
mylladdr net.IP mylladdr net.IP
mymac macAddress mymac macAddress
peermacs map[address.Address]neighbor peermacs map[address.Address]neighbor
@ -59,7 +59,7 @@ func ipv6Header_Marshal(h *ipv6.Header) ([]byte, error) {
// Initialises the ICMPv6 module by assigning our link-local IPv6 address and // Initialises the ICMPv6 module by assigning our link-local IPv6 address and
// our MAC address. ICMPv6 messages will always appear to originate from these // our MAC address. ICMPv6 messages will always appear to originate from these
// addresses. // addresses.
func (i *icmpv6) init(t *tunAdapter) { func (i *icmpv6) init(t *TunAdapter) {
i.tun = t i.tun = t
i.peermacs = make(map[address.Address]neighbor) i.peermacs = make(map[address.Address]neighbor)
@ -69,8 +69,8 @@ func (i *icmpv6) init(t *tunAdapter) {
i.mylladdr = net.IP{ i.mylladdr = net.IP{
0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFE} 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFE}
copy(i.mymac[:], i.tun.core.router.addr[:]) copy(i.mymac[:], i.tun.addr[:])
copy(i.mylladdr[9:], i.tun.core.router.addr[1:]) copy(i.mylladdr[9:], i.tun.addr[1:])
} }
// Parses an incoming ICMPv6 packet. The packet provided may be either an // Parses an incoming ICMPv6 packet. The packet provided may be either an
@ -162,7 +162,7 @@ func (i *icmpv6) parse_packet_tun(datain []byte, datamac *[]byte) ([]byte, error
response, err := i.handle_ndp(datain[ipv6.HeaderLen:]) response, err := i.handle_ndp(datain[ipv6.HeaderLen:])
if err == nil { if err == nil {
// Create our ICMPv6 response // Create our ICMPv6 response
responsePacket, err := i.create_icmpv6_tun( responsePacket, err := i.Create_ICMPv6_TUN(
ipv6Header.Src, i.mylladdr, ipv6Header.Src, i.mylladdr,
ipv6.ICMPTypeNeighborAdvertisement, 0, ipv6.ICMPTypeNeighborAdvertisement, 0,
&icmp.DefaultMessageBody{Data: response}) &icmp.DefaultMessageBody{Data: response})
@ -202,9 +202,9 @@ func (i *icmpv6) parse_packet_tun(datain []byte, datamac *[]byte) ([]byte, error
// Creates an ICMPv6 packet based on the given icmp.MessageBody and other // Creates an ICMPv6 packet based on the given icmp.MessageBody and other
// parameters, complete with ethernet and IP headers, which can be written // parameters, complete with ethernet and IP headers, which can be written
// directly to a TAP adapter. // 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) { 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 // Pass through to create_icmpv6_tun
ipv6packet, err := i.create_icmpv6_tun(dst, src, mtype, mcode, mbody) ipv6packet, err := i.Create_ICMPv6_TUN(dst, src, mtype, mcode, mbody)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -226,7 +226,7 @@ func (i *icmpv6) create_icmpv6_tap(dstmac macAddress, dst net.IP, src net.IP, mt
// parameters, complete with IP headers only, which can be written directly to // 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 // a TUN adapter, or called directly by the create_icmpv6_tap function when
// generating a message for TAP adapters. // 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) { 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 // Create the ICMPv6 message
icmpMessage := icmp.Message{ icmpMessage := icmp.Message{
Type: mtype, Type: mtype,
@ -287,7 +287,7 @@ func (i *icmpv6) create_ndp_tap(dst address.Address) ([]byte, error) {
copy(dstmac[2:6], dstaddr[12:16]) copy(dstmac[2:6], dstaddr[12:16])
// Create the ND request // Create the ND request
requestPacket, err := i.create_icmpv6_tap( requestPacket, err := i.Create_ICMPv6_TAP(
dstmac, dstaddr[:], i.mylladdr, dstmac, dstaddr[:], i.mylladdr,
ipv6.ICMPTypeNeighborSolicitation, 0, ipv6.ICMPTypeNeighborSolicitation, 0,
&icmp.DefaultMessageBody{Data: payload[:]}) &icmp.DefaultMessageBody{Data: payload[:]})

View file

@ -1,4 +1,4 @@
package yggdrasil package tuntap
// This manages the tun driver to send/recv packets to/from applications // This manages the tun driver to send/recv packets to/from applications
@ -10,10 +10,14 @@ import (
"sync" "sync"
"time" "time"
"github.com/gologme/log"
"github.com/songgao/packets/ethernet" "github.com/songgao/packets/ethernet"
"github.com/yggdrasil-network/water" "github.com/yggdrasil-network/water"
"github.com/yggdrasil-network/yggdrasil-go/src/adapter"
"github.com/yggdrasil-network/yggdrasil-go/src/address" "github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/config"
"github.com/yggdrasil-network/yggdrasil-go/src/defaults" "github.com/yggdrasil-network/yggdrasil-go/src/defaults"
"github.com/yggdrasil-network/yggdrasil-go/src/util" "github.com/yggdrasil-network/yggdrasil-go/src/util"
) )
@ -22,9 +26,11 @@ const tun_IPv6_HEADER_LENGTH = 40
const tun_ETHER_HEADER_LENGTH = 14 const tun_ETHER_HEADER_LENGTH = 14
// Represents a running TUN/TAP interface. // Represents a running TUN/TAP interface.
type tunAdapter struct { type TunAdapter struct {
Adapter adapter.Adapter
icmpv6 icmpv6 addr address.Address
subnet address.Subnet
Icmpv6 icmpv6
mtu int mtu int
iface *water.Interface iface *water.Interface
mutex sync.RWMutex // Protects the below mutex sync.RWMutex // Protects the below
@ -33,27 +39,39 @@ type tunAdapter struct {
// Gets the maximum supported MTU for the platform based on the defaults in // Gets the maximum supported MTU for the platform based on the defaults in
// defaults.GetDefaults(). // defaults.GetDefaults().
func getSupportedMTU(mtu int) int { func GetSupportedMTU(mtu int) int {
if mtu > defaults.GetDefaults().MaximumIfMTU { if mtu > defaults.GetDefaults().MaximumIfMTU {
return defaults.GetDefaults().MaximumIfMTU return defaults.GetDefaults().MaximumIfMTU
} }
return mtu return mtu
} }
func (tun *TunAdapter) GetMTU() int {
return GetSupportedMTU(tun.mtu)
}
func (tun *TunAdapter) GetTAPMode() bool {
return tun.iface.IsTAP()
}
func (tun *TunAdapter) GetName() string {
return tun.iface.Name()
}
// Initialises the TUN/TAP adapter. // Initialises the TUN/TAP adapter.
func (tun *tunAdapter) init(core *Core, send chan<- []byte, recv <-chan []byte) { func (tun *TunAdapter) Init(config *config.StatefulNodeConfig, log *log.Logger, send chan<- []byte, recv <-chan []byte) {
tun.Adapter.init(core, send, recv) tun.Adapter.Init(config, log, send, recv)
tun.icmpv6.init(tun) tun.Icmpv6.init(tun)
go func() { go func() {
for { for {
e := <-tun.reconfigure e := <-tun.Reconfigure
tun.core.configMutex.RLock() tun.Config.Mutex.RLock()
updated := tun.core.config.IfName != tun.core.configOld.IfName || updated := tun.Config.Current.IfName != tun.Config.Previous.IfName ||
tun.core.config.IfTAPMode != tun.core.configOld.IfTAPMode || tun.Config.Current.IfTAPMode != tun.Config.Previous.IfTAPMode ||
tun.core.config.IfMTU != tun.core.configOld.IfMTU tun.Config.Current.IfMTU != tun.Config.Previous.IfMTU
tun.core.configMutex.RUnlock() tun.Config.Mutex.RUnlock()
if updated { if updated {
tun.core.log.Warnln("Reconfiguring TUN/TAP is not supported yet") tun.Log.Warnln("Reconfiguring TUN/TAP is not supported yet")
e <- nil e <- nil
} else { } else {
e <- nil e <- nil
@ -64,15 +82,17 @@ func (tun *tunAdapter) init(core *Core, send chan<- []byte, recv <-chan []byte)
// Starts the setup process for the TUN/TAP adapter, and if successful, starts // Starts the setup process for the TUN/TAP adapter, and if successful, starts
// the read/write goroutines to handle packets on that interface. // the read/write goroutines to handle packets on that interface.
func (tun *tunAdapter) start() error { func (tun *TunAdapter) Start(addrobj address.Address, subnetobj address.Subnet) error {
tun.core.configMutex.RLock() tun.addr = addrobj
ifname := tun.core.config.IfName tun.subnet = subnetobj
iftapmode := tun.core.config.IfTAPMode tun.Config.Mutex.RLock()
addr := fmt.Sprintf("%s/%d", net.IP(tun.core.router.addr[:]).String(), 8*len(address.GetPrefix())-1) ifname := tun.Config.Current.IfName
mtu := tun.core.config.IfMTU iftapmode := tun.Config.Current.IfTAPMode
tun.core.configMutex.RUnlock() addr := fmt.Sprintf("%s/%d", net.IP(tun.addr[:]).String(), 8*len(address.GetPrefix())-1)
mtu := tun.Config.Current.IfMTU
tun.Config.Mutex.RUnlock()
if ifname != "none" { if ifname != "none" {
if err := tun.setup(ifname, iftapmode, addr, mtu); err != nil { if err := tun.Setup(ifname, iftapmode, addr, mtu); err != nil {
return err return err
} }
} }
@ -82,15 +102,15 @@ func (tun *tunAdapter) start() error {
tun.mutex.Lock() tun.mutex.Lock()
tun.isOpen = true tun.isOpen = true
tun.mutex.Unlock() tun.mutex.Unlock()
go func() { tun.core.log.Errorln("WARNING: tun.read() exited with error:", tun.read()) }() go func() { tun.Log.Errorln("WARNING: tun.Read() exited with error:", tun.Read()) }()
go func() { tun.core.log.Errorln("WARNING: tun.write() exited with error:", tun.write()) }() go func() { tun.Log.Errorln("WARNING: tun.Write() exited with error:", tun.Write()) }()
if iftapmode { if iftapmode {
go func() { go func() {
for { for {
if _, ok := tun.icmpv6.peermacs[tun.core.router.addr]; ok { if _, ok := tun.Icmpv6.peermacs[tun.addr]; ok {
break break
} }
request, err := tun.icmpv6.create_ndp_tap(tun.core.router.addr) request, err := tun.Icmpv6.create_ndp_tap(tun.addr)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -107,9 +127,9 @@ func (tun *tunAdapter) start() error {
// Writes a packet to the TUN/TAP adapter. If the adapter is running in TAP // 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 // mode then additional ethernet encapsulation is added for the benefit of the
// host operating system. // host operating system.
func (tun *tunAdapter) write() error { func (tun *TunAdapter) Write() error {
for { for {
data := <-tun.recv data := <-tun.Recv
if tun.iface == nil { if tun.iface == nil {
continue continue
} }
@ -129,17 +149,17 @@ func (tun *tunAdapter) write() error {
return errors.New("Invalid address family") return errors.New("Invalid address family")
} }
sendndp := func(destAddr address.Address) { sendndp := func(destAddr address.Address) {
neigh, known := tun.icmpv6.peermacs[destAddr] neigh, known := tun.Icmpv6.peermacs[destAddr]
known = known && (time.Since(neigh.lastsolicitation).Seconds() < 30) known = known && (time.Since(neigh.lastsolicitation).Seconds() < 30)
if !known { if !known {
request, err := tun.icmpv6.create_ndp_tap(destAddr) request, err := tun.Icmpv6.create_ndp_tap(destAddr)
if err != nil { if err != nil {
panic(err) panic(err)
} }
if _, err := tun.iface.Write(request); err != nil { if _, err := tun.iface.Write(request); err != nil {
panic(err) panic(err)
} }
tun.icmpv6.peermacs[destAddr] = neighbor{ tun.Icmpv6.peermacs[destAddr] = neighbor{
lastsolicitation: time.Now(), lastsolicitation: time.Now(),
} }
} }
@ -147,21 +167,21 @@ func (tun *tunAdapter) write() error {
var peermac macAddress var peermac macAddress
var peerknown bool var peerknown bool
if data[0]&0xf0 == 0x40 { if data[0]&0xf0 == 0x40 {
destAddr = tun.core.router.addr destAddr = tun.addr
} else if data[0]&0xf0 == 0x60 { } 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]) { if !bytes.Equal(tun.addr[:16], destAddr[:16]) && !bytes.Equal(tun.subnet[:8], destAddr[:8]) {
destAddr = tun.core.router.addr destAddr = tun.addr
} }
} }
if neighbor, ok := tun.icmpv6.peermacs[destAddr]; ok && neighbor.learned { if neighbor, ok := tun.Icmpv6.peermacs[destAddr]; ok && neighbor.learned {
peermac = neighbor.mac peermac = neighbor.mac
peerknown = true peerknown = true
} else if neighbor, ok := tun.icmpv6.peermacs[tun.core.router.addr]; ok && neighbor.learned { } else if neighbor, ok := tun.Icmpv6.peermacs[tun.addr]; ok && neighbor.learned {
peermac = neighbor.mac peermac = neighbor.mac
peerknown = true peerknown = true
sendndp(destAddr) sendndp(destAddr)
} else { } else {
sendndp(tun.core.router.addr) sendndp(tun.addr)
} }
if peerknown { if peerknown {
var proto ethernet.Ethertype var proto ethernet.Ethertype
@ -174,7 +194,7 @@ func (tun *tunAdapter) write() error {
var frame ethernet.Frame var frame ethernet.Frame
frame.Prepare( frame.Prepare(
peermac[:6], // Destination MAC address peermac[:6], // Destination MAC address
tun.icmpv6.mymac[:6], // Source MAC address tun.Icmpv6.mymac[:6], // Source MAC address
ethernet.NotTagged, // VLAN tagging ethernet.NotTagged, // VLAN tagging
proto, // Ethertype proto, // Ethertype
len(data)) // Payload length len(data)) // Payload length
@ -210,7 +230,7 @@ func (tun *tunAdapter) write() error {
// is running in TAP mode then the ethernet headers will automatically be // is running in TAP mode then the ethernet headers will automatically be
// processed and stripped if necessary. If an ICMPv6 packet is found, then // processed and stripped if necessary. If an ICMPv6 packet is found, then
// the relevant helper functions in icmpv6.go are called. // the relevant helper functions in icmpv6.go are called.
func (tun *tunAdapter) read() error { func (tun *TunAdapter) Read() error {
mtu := tun.mtu mtu := tun.mtu
if tun.iface.IsTAP() { if tun.iface.IsTAP() {
mtu += tun_ETHER_HEADER_LENGTH mtu += tun_ETHER_HEADER_LENGTH
@ -244,18 +264,18 @@ func (tun *tunAdapter) read() error {
// Found an ICMPv6 packet // Found an ICMPv6 packet
b := make([]byte, n) b := make([]byte, n)
copy(b, buf) copy(b, buf)
go tun.icmpv6.parse_packet(b) go tun.Icmpv6.parse_packet(b)
} }
} }
packet := append(util.GetBytes(), buf[o:n]...) packet := append(util.GetBytes(), buf[o:n]...)
tun.send <- packet tun.Send <- packet
} }
} }
// Closes the TUN/TAP adapter. This is only usually called when the Yggdrasil // Closes the TUN/TAP adapter. This is only usually called when the Yggdrasil
// process stops. Typically this operation will happen quickly, but on macOS // process stops. Typically this operation will happen quickly, but on macOS
// it can block until a read operation is completed. // it can block until a read operation is completed.
func (tun *tunAdapter) close() error { func (tun *TunAdapter) Close() error {
tun.mutex.Lock() tun.mutex.Lock()
tun.isOpen = false tun.isOpen = false
tun.mutex.Unlock() tun.mutex.Unlock()

View file

@ -1,6 +1,6 @@
// +build openbsd freebsd netbsd // +build openbsd freebsd netbsd
package yggdrasil package tuntap
import ( import (
"encoding/binary" "encoding/binary"
@ -77,7 +77,7 @@ type in6_ifreq_lifetime struct {
// a system socket and making syscalls to the kernel. This is not refined though // 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 // and often doesn't work (if at all), therefore if a call fails, it resorts
// to calling "ifconfig" instead. // to calling "ifconfig" instead.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error { func (tun *TunAdapter) Setup(ifname string, iftapmode bool, addr string, mtu int) error {
var config water.Config var config water.Config
if ifname[:4] == "auto" { if ifname[:4] == "auto" {
ifname = "/dev/tap0" ifname = "/dev/tap0"
@ -103,7 +103,7 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
return tun.setupAddress(addr) return tun.setupAddress(addr)
} }
func (tun *tunAdapter) setupAddress(addr string) error { func (tun *TunAdapter) setupAddress(addr string) error {
var sfd int var sfd int
var err error var err error

View file

@ -1,6 +1,6 @@
// +build !mobile // +build !mobile
package yggdrasil package tuntap
// The darwin platform specific tun parts // The darwin platform specific tun parts
@ -16,9 +16,9 @@ import (
) )
// Configures the "utun" adapter with the correct IPv6 address and MTU. // Configures the "utun" adapter with the correct IPv6 address and MTU.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error { func (tun *TunAdapter) Setup(ifname string, iftapmode bool, addr string, mtu int) error {
if iftapmode { if iftapmode {
tun.core.log.Warnln("TAP mode is not supported on this platform, defaulting to TUN") tun.Log.Warnln("TAP mode is not supported on this platform, defaulting to TUN")
} }
config := water.Config{DeviceType: water.TUN} config := water.Config{DeviceType: water.TUN}
iface, err := water.New(config) iface, err := water.New(config)
@ -26,7 +26,7 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
panic(err) panic(err)
} }
tun.iface = iface tun.iface = iface
tun.mtu = getSupportedMTU(mtu) tun.mtu = GetSupportedMTU(mtu)
return tun.setupAddress(addr) return tun.setupAddress(addr)
} }
@ -64,12 +64,12 @@ type ifreq struct {
// Sets the IPv6 address of the utun adapter. On Darwin/macOS this is done using // 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. // a system socket and making direct syscalls to the kernel.
func (tun *tunAdapter) setupAddress(addr string) error { func (tun *TunAdapter) setupAddress(addr string) error {
var fd int var fd int
var err error var err error
if fd, err = unix.Socket(unix.AF_INET6, unix.SOCK_DGRAM, 0); err != nil { 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) tun.Log.Printf("Create AF_SYSTEM socket failed: %v.", err)
return err return err
} }
@ -98,19 +98,19 @@ func (tun *tunAdapter) setupAddress(addr string) error {
copy(ir.ifr_name[:], tun.iface.Name()) copy(ir.ifr_name[:], tun.iface.Name())
ir.ifru_mtu = uint32(tun.mtu) ir.ifru_mtu = uint32(tun.mtu)
tun.core.log.Infof("Interface name: %s", ar.ifra_name) tun.Log.Infof("Interface name: %s", ar.ifra_name)
tun.core.log.Infof("Interface IPv6: %s", addr) tun.Log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", ir.ifru_mtu) tun.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 { if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(darwin_SIOCAIFADDR_IN6), uintptr(unsafe.Pointer(&ar))); errno != 0 {
err = errno err = errno
tun.core.log.Errorf("Error in darwin_SIOCAIFADDR_IN6: %v", errno) tun.Log.Errorf("Error in darwin_SIOCAIFADDR_IN6: %v", errno)
return err return err
} }
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(unix.SIOCSIFMTU), uintptr(unsafe.Pointer(&ir))); errno != 0 { if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(unix.SIOCSIFMTU), uintptr(unsafe.Pointer(&ir))); errno != 0 {
err = errno err = errno
tun.core.log.Errorf("Error in SIOCSIFMTU: %v", errno) tun.Log.Errorf("Error in SIOCSIFMTU: %v", errno)
return err return err
} }

View file

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

View file

@ -1,6 +1,6 @@
// +build !mobile // +build !mobile
package yggdrasil package tuntap
// The linux platform specific tun parts // The linux platform specific tun parts
@ -15,7 +15,7 @@ import (
) )
// Configures the TAP adapter with the correct IPv6 address and MTU. // Configures the TAP adapter with the correct IPv6 address and MTU.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error { func (tun *TunAdapter) Setup(ifname string, iftapmode bool, addr string, mtu int) error {
var config water.Config var config water.Config
if iftapmode { if iftapmode {
config = water.Config{DeviceType: water.TAP} config = water.Config{DeviceType: water.TAP}
@ -50,7 +50,7 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
// is used to do this, so there is not a hard requirement on "ip" or "ifconfig" // 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 // to exist on the system, but this will fail if Netlink is not present in the
// kernel (it nearly always is). // kernel (it nearly always is).
func (tun *tunAdapter) setupAddress(addr string) error { func (tun *TunAdapter) setupAddress(addr string) error {
// Set address // Set address
var netIF *net.Interface var netIF *net.Interface
ifces, err := net.Interfaces() ifces, err := net.Interfaces()

View file

@ -1,6 +1,6 @@
// +build !linux,!darwin,!windows,!openbsd,!freebsd,!netbsd,!mobile // +build !linux,!darwin,!windows,!openbsd,!freebsd,!netbsd,!mobile
package yggdrasil package tuntap
import water "github.com/yggdrasil-network/water" import water "github.com/yggdrasil-network/water"
@ -9,7 +9,7 @@ import water "github.com/yggdrasil-network/water"
// Creates the TUN/TAP adapter, if supported by the Water library. Note that // Creates the TUN/TAP adapter, if supported by the Water library. Note that
// no guarantees are made at this point on an unsupported platform. // no guarantees are made at this point on an unsupported platform.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error { func (tun *TunAdapter) Setup(ifname string, iftapmode bool, addr string, mtu int) error {
var config water.Config var config water.Config
if iftapmode { if iftapmode {
config = water.Config{DeviceType: water.TAP} config = water.Config{DeviceType: water.TAP}
@ -27,7 +27,7 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
// We don't know how to set the IPv6 address on an unknown platform, therefore // 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. // write about it to stdout and don't try to do anything further.
func (tun *tunAdapter) setupAddress(addr string) error { 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) tun.core.log.Warnln("Platform not supported, you must set the address of", tun.iface.Name(), "to", addr)
return nil return nil
} }

View file

@ -1,4 +1,4 @@
package yggdrasil package tuntap
import ( import (
"fmt" "fmt"
@ -13,7 +13,7 @@ import (
// Configures the TAP adapter with the correct IPv6 address and MTU. On Windows // 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 // we don't make use of a direct operating system API to do this - we instead
// delegate the hard work to "netsh". // delegate the hard work to "netsh".
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error { func (tun *TunAdapter) Setup(ifname string, iftapmode bool, addr string, mtu int) error {
if !iftapmode { if !iftapmode {
tun.core.log.Warnln("TUN mode is not supported on this platform, defaulting to TAP") tun.core.log.Warnln("TUN mode is not supported on this platform, defaulting to TAP")
} }
@ -65,7 +65,7 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
} }
// Sets the MTU of the TAP adapter. // Sets the MTU of the TAP adapter.
func (tun *tunAdapter) setupMTU(mtu int) error { func (tun *TunAdapter) setupMTU(mtu int) error {
// Set MTU // Set MTU
cmd := exec.Command("netsh", "interface", "ipv6", "set", "subinterface", cmd := exec.Command("netsh", "interface", "ipv6", "set", "subinterface",
fmt.Sprintf("interface=%s", tun.iface.Name()), fmt.Sprintf("interface=%s", tun.iface.Name()),
@ -82,7 +82,7 @@ func (tun *tunAdapter) setupMTU(mtu int) error {
} }
// Sets the IPv6 address of the TAP adapter. // Sets the IPv6 address of the TAP adapter.
func (tun *tunAdapter) setupAddress(addr string) error { func (tun *TunAdapter) setupAddress(addr string) error {
// Set address // Set address
cmd := exec.Command("netsh", "interface", "ipv6", "add", "address", cmd := exec.Command("netsh", "interface", "ipv6", "add", "address",
fmt.Sprintf("interface=%s", tun.iface.Name()), fmt.Sprintf("interface=%s", tun.iface.Name()),

View file

@ -1,18 +0,0 @@
package yggdrasil
// Defines the minimum required struct members for an adapter type (this is
// now the base type for tunAdapter in tun.go)
type Adapter struct {
core *Core
send chan<- []byte
recv <-chan []byte
reconfigure chan chan 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)
}

View file

@ -16,7 +16,6 @@ import (
"github.com/yggdrasil-network/yggdrasil-go/src/address" "github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto" "github.com/yggdrasil-network/yggdrasil-go/src/crypto"
"github.com/yggdrasil-network/yggdrasil-go/src/defaults"
) )
// TODO: Add authentication // TODO: Add authentication
@ -58,19 +57,19 @@ func (a *admin) init(c *Core) {
go func() { go func() {
for { for {
e := <-a.reconfigure e := <-a.reconfigure
a.core.configMutex.RLock() a.core.config.Mutex.RLock()
if a.core.config.AdminListen != a.core.configOld.AdminListen { if a.core.config.Current.AdminListen != a.core.config.Previous.AdminListen {
a.listenaddr = a.core.config.AdminListen a.listenaddr = a.core.config.Current.AdminListen
a.close() a.close()
a.start() a.start()
} }
a.core.configMutex.RUnlock() a.core.config.Mutex.RUnlock()
e <- nil e <- nil
} }
}() }()
a.core.configMutex.RLock() a.core.config.Mutex.RLock()
a.listenaddr = a.core.config.AdminListen a.listenaddr = a.core.config.Current.AdminListen
a.core.configMutex.RUnlock() a.core.config.Mutex.RUnlock()
a.addHandler("list", []string{}, func(in admin_info) (admin_info, error) { a.addHandler("list", []string{}, func(in admin_info) (admin_info, error) {
handlers := make(map[string]interface{}) handlers := make(map[string]interface{})
for _, handler := range a.handlers { for _, handler := range a.handlers {
@ -180,13 +179,13 @@ func (a *admin) init(c *Core) {
}() }()
return admin_info{ return admin_info{
a.core.router.tun.iface.Name(): admin_info{ a.core.router.tun.GetName(): admin_info{
"tap_mode": a.core.router.tun.iface.IsTAP(), "tap_mode": a.core.router.tun.GetTAPMode(),
"mtu": a.core.router.tun.mtu, "mtu": a.core.router.tun.GetMTU(),
}, },
}, nil }, nil
}) })
a.addHandler("setTunTap", []string{"name", "[tap_mode]", "[mtu]"}, func(in admin_info) (admin_info, error) { /*a.addHandler("setTunTap", []string{"name", "[tap_mode]", "[mtu]"}, func(in admin_info) (admin_info, error) {
// Set sane defaults // Set sane defaults
iftapmode := defaults.GetDefaults().DefaultIfTAPMode iftapmode := defaults.GetDefaults().DefaultIfTAPMode
ifmtu := defaults.GetDefaults().DefaultIfMTU ifmtu := defaults.GetDefaults().DefaultIfMTU
@ -211,7 +210,7 @@ func (a *admin) init(c *Core) {
}, },
}, nil }, nil
} }
}) })*/
a.addHandler("getMulticastInterfaces", []string{}, func(in admin_info) (admin_info, error) { a.addHandler("getMulticastInterfaces", []string{}, func(in admin_info) (admin_info, error) {
var intfs []string var intfs []string
for _, v := range a.core.multicast.interfaces() { for _, v := range a.core.multicast.interfaces() {
@ -609,7 +608,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. // 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 { /*func (a *admin) startTunWithMTU(ifname string, iftapmode bool, ifmtu int) error {
// Close the TUN first if open // Close the TUN first if open
_ = a.core.router.tun.close() _ = a.core.router.tun.close()
// Then reconfigure and start it // Then reconfigure and start it
@ -635,7 +634,7 @@ func (a *admin) startTunWithMTU(ifname string, iftapmode bool, ifmtu int) error
} }
go a.core.router.tun.write() go a.core.router.tun.write()
return nil return nil
} }*/
// getData_getSelf returns the self node's info for admin responses. // getData_getSelf returns the self node's info for admin responses.
func (a *admin) getData_getSelf() *admin_nodeInfo { func (a *admin) getData_getSelf() *admin_nodeInfo {

View file

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

View file

@ -4,7 +4,6 @@ import (
"encoding/hex" "encoding/hex"
"io/ioutil" "io/ioutil"
"net" "net"
"sync"
"time" "time"
"github.com/gologme/log" "github.com/gologme/log"
@ -29,9 +28,7 @@ type Core struct {
// This is the main data structure that holds everything else for a node // 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 // 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 // guarantee that it will be covered by the mutex
config config.NodeConfig // Active config config config.StatefulNodeConfig
configOld config.NodeConfig // Previous config
configMutex sync.RWMutex // Protects both config and configOld
boxPub crypto.BoxPubKey boxPub crypto.BoxPubKey
boxPriv crypto.BoxPrivKey boxPriv crypto.BoxPrivKey
sigPub crypto.SigPubKey sigPub crypto.SigPubKey
@ -57,19 +54,19 @@ func (c *Core) init() error {
c.log = log.New(ioutil.Discard, "", 0) c.log = log.New(ioutil.Discard, "", 0)
} }
boxPubHex, err := hex.DecodeString(c.config.EncryptionPublicKey) boxPubHex, err := hex.DecodeString(c.config.Current.EncryptionPublicKey)
if err != nil { if err != nil {
return err return err
} }
boxPrivHex, err := hex.DecodeString(c.config.EncryptionPrivateKey) boxPrivHex, err := hex.DecodeString(c.config.Current.EncryptionPrivateKey)
if err != nil { if err != nil {
return err return err
} }
sigPubHex, err := hex.DecodeString(c.config.SigningPublicKey) sigPubHex, err := hex.DecodeString(c.config.Current.SigningPublicKey)
if err != nil { if err != nil {
return err return err
} }
sigPrivHex, err := hex.DecodeString(c.config.SigningPrivateKey) sigPrivHex, err := hex.DecodeString(c.config.Current.SigningPrivateKey)
if err != nil { if err != nil {
return err return err
} }
@ -97,10 +94,10 @@ func (c *Core) init() error {
func (c *Core) addPeerLoop() { func (c *Core) addPeerLoop() {
for { for {
// Get the peers from the config - these could change! // Get the peers from the config - these could change!
c.configMutex.RLock() c.config.Mutex.RLock()
peers := c.config.Peers peers := c.config.Current.Peers
interfacepeers := c.config.InterfacePeers interfacepeers := c.config.Current.InterfacePeers
c.configMutex.RUnlock() c.config.Mutex.RUnlock()
// Add peers from the Peers section // Add peers from the Peers section
for _, peer := range peers { for _, peer := range peers {
@ -126,10 +123,10 @@ func (c *Core) addPeerLoop() {
func (c *Core) UpdateConfig(config *config.NodeConfig) { func (c *Core) UpdateConfig(config *config.NodeConfig) {
c.log.Infoln("Reloading configuration...") c.log.Infoln("Reloading configuration...")
c.configMutex.Lock() c.config.Mutex.Lock()
c.configOld = c.config c.config.Previous = c.config.Current
c.config = *config c.config.Current = *config
c.configMutex.Unlock() c.config.Mutex.Unlock()
errors := 0 errors := 0
@ -140,7 +137,7 @@ func (c *Core) UpdateConfig(config *config.NodeConfig) {
c.sessions.reconfigure, c.sessions.reconfigure,
c.peers.reconfigure, c.peers.reconfigure,
c.router.reconfigure, c.router.reconfigure,
c.router.tun.reconfigure, c.router.tun.Reconfigure,
c.router.cryptokey.reconfigure, c.router.cryptokey.reconfigure,
c.switchTable.reconfigure, c.switchTable.reconfigure,
c.link.reconfigure, c.link.reconfigure,
@ -197,10 +194,10 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
c.log.Infoln("Starting up...") c.log.Infoln("Starting up...")
c.configMutex.Lock() c.config.Mutex.Lock()
c.config = *nc c.config.Current = *nc
c.configOld = c.config c.config.Previous = *nc
c.configMutex.Unlock() c.config.Mutex.Unlock()
c.init() c.init()
@ -233,7 +230,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
return err 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") c.log.Errorln("Failed to start TUN/TAP")
return err return err
} }
@ -247,7 +244,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
// Stops the Yggdrasil node. // Stops the Yggdrasil node.
func (c *Core) Stop() { func (c *Core) Stop() {
c.log.Infoln("Stopping...") c.log.Infoln("Stopping...")
c.router.tun.close() c.router.tun.Close()
c.admin.close() c.admin.close()
} }
@ -343,10 +340,10 @@ func (c *Core) GetTUNDefaultIfTAPMode() bool {
// Gets the current TUN/TAP interface name. // Gets the current TUN/TAP interface name.
func (c *Core) GetTUNIfName() string { func (c *Core) GetTUNIfName() string {
return c.router.tun.iface.Name() return c.router.tun.GetName()
} }
// Gets the current TUN/TAP interface MTU. // Gets the current TUN/TAP interface MTU.
func (c *Core) GetTUNIfMTU() int { func (c *Core) GetTUNIfMTU() int {
return c.router.tun.mtu return c.router.tun.GetMTU()
} }

View file

@ -25,7 +25,7 @@ import "os"
import "github.com/gologme/log" import "github.com/gologme/log"
import "github.com/yggdrasil-network/yggdrasil-go/src/address" import "github.com/yggdrasil-network/yggdrasil-go/src/address"
import "github.com/yggdrasil-network/yggdrasil-go/src/config" import "github.com/yggdrasil-network/yggdrasil-go/src.config.Current.
import "github.com/yggdrasil-network/yggdrasil-go/src/crypto" import "github.com/yggdrasil-network/yggdrasil-go/src/crypto"
import "github.com/yggdrasil-network/yggdrasil-go/src/defaults" import "github.com/yggdrasil-network/yggdrasil-go/src/defaults"
@ -59,7 +59,7 @@ func (c *Core) Init() {
hbpriv := hex.EncodeToString(bpriv[:]) hbpriv := hex.EncodeToString(bpriv[:])
hspub := hex.EncodeToString(spub[:]) hspub := hex.EncodeToString(spub[:])
hspriv := hex.EncodeToString(spriv[:]) hspriv := hex.EncodeToString(spriv[:])
c.config = config.NodeConfig{ c.config.Current.= config.NodeConfig{
EncryptionPublicKey: hbpub, EncryptionPublicKey: hbpub,
EncryptionPrivateKey: hbpriv, EncryptionPrivateKey: hbpriv,
SigningPublicKey: hspub, SigningPublicKey: hspub,
@ -382,7 +382,7 @@ func (c *Core) DEBUG_init(bpub []byte,
hbpriv := hex.EncodeToString(bpriv[:]) hbpriv := hex.EncodeToString(bpriv[:])
hspub := hex.EncodeToString(spub[:]) hspub := hex.EncodeToString(spub[:])
hspriv := hex.EncodeToString(spriv[:]) hspriv := hex.EncodeToString(spriv[:])
c.config = config.NodeConfig{ c.config.Current.= config.NodeConfig{
EncryptionPublicKey: hbpub, EncryptionPublicKey: hbpub,
EncryptionPrivateKey: hbpriv, EncryptionPrivateKey: hbpriv,
SigningPublicKey: hspub, SigningPublicKey: hspub,
@ -457,7 +457,7 @@ func (c *Core) DEBUG_addSOCKSConn(socksaddr, peeraddr string) {
//* //*
func (c *Core) DEBUG_setupAndStartGlobalTCPInterface(addrport string) { func (c *Core) DEBUG_setupAndStartGlobalTCPInterface(addrport string) {
c.config.Listen = []string{addrport} c.config.Current.Listen = []string{addrport}
if err := c.link.init(c); err != nil { if err := c.link.init(c); err != nil {
c.log.Println("Failed to start interfaces:", err) c.log.Println("Failed to start interfaces:", err)
panic(err) panic(err)
@ -505,7 +505,7 @@ func (c *Core) DEBUG_addKCPConn(saddr string) {
func (c *Core) DEBUG_setupAndStartAdminInterface(addrport string) { func (c *Core) DEBUG_setupAndStartAdminInterface(addrport string) {
a := admin{} a := admin{}
c.config.AdminListen = addrport c.config.Current.AdminListen = addrport
a.init(c /*, addrport*/) a.init(c /*, addrport*/)
c.admin = a c.admin = a
} }

View file

@ -12,7 +12,7 @@ import (
hjson "github.com/hjson/hjson-go" hjson "github.com/hjson/hjson-go"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
"github.com/yggdrasil-network/yggdrasil-go/src/config" "github.com/yggdrasil-network/yggdrasil-go/src.config.Current.
"github.com/yggdrasil-network/yggdrasil-go/src/util" "github.com/yggdrasil-network/yggdrasil-go/src/util"
) )

View file

@ -23,9 +23,9 @@ func (m *multicast) init(core *Core) {
m.core = core m.core = core
m.reconfigure = make(chan chan error, 1) m.reconfigure = make(chan chan error, 1)
m.listeners = make(map[string]*tcpListener) m.listeners = make(map[string]*tcpListener)
m.core.configMutex.RLock() m.core.config.Mutex.RLock()
m.listenPort = m.core.config.LinkLocalTCPPort m.listenPort = m.core.config.Current.LinkLocalTCPPort
m.core.configMutex.RUnlock() m.core.config.Mutex.RUnlock()
go func() { go func() {
for { for {
e := <-m.reconfigure e := <-m.reconfigure
@ -70,9 +70,9 @@ func (m *multicast) start() error {
func (m *multicast) interfaces() map[string]net.Interface { func (m *multicast) interfaces() map[string]net.Interface {
// Get interface expressions from config // Get interface expressions from config
m.core.configMutex.RLock() m.core.config.Mutex.RLock()
exprs := m.core.config.MulticastInterfaces exprs := m.core.config.Current.MulticastInterfaces
m.core.configMutex.RUnlock() m.core.config.Mutex.RUnlock()
// Ask the system for network interfaces // Ask the system for network interfaces
interfaces := make(map[string]net.Interface) interfaces := make(map[string]net.Interface)
allifaces, err := net.Interfaces() 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. // because the key is in the whitelist or because the whitelist is empty.
func (ps *peers) isAllowedEncryptionPublicKey(box *crypto.BoxPubKey) bool { func (ps *peers) isAllowedEncryptionPublicKey(box *crypto.BoxPubKey) bool {
boxstr := hex.EncodeToString(box[:]) boxstr := hex.EncodeToString(box[:])
ps.core.configMutex.RLock() ps.core.config.Mutex.RLock()
defer ps.core.configMutex.RUnlock() defer ps.core.config.Mutex.RUnlock()
for _, v := range ps.core.config.AllowedEncryptionPublicKeys { for _, v := range ps.core.config.Current.AllowedEncryptionPublicKeys {
if v == boxstr { if v == boxstr {
return true return true
} }
} }
return len(ps.core.config.AllowedEncryptionPublicKeys) == 0 return len(ps.core.config.Current.AllowedEncryptionPublicKeys) == 0
} }
// Adds a key to the whitelist. // Adds a key to the whitelist.
func (ps *peers) addAllowedEncryptionPublicKey(box string) { func (ps *peers) addAllowedEncryptionPublicKey(box string) {
ps.core.configMutex.RLock() ps.core.config.Mutex.RLock()
defer ps.core.configMutex.RUnlock() defer ps.core.config.Mutex.RUnlock()
ps.core.config.AllowedEncryptionPublicKeys = ps.core.config.Current.AllowedEncryptionPublicKeys =
append(ps.core.config.AllowedEncryptionPublicKeys, box) append(ps.core.config.Current.AllowedEncryptionPublicKeys, box)
} }
// Removes a key from the whitelist. // Removes a key from the whitelist.
func (ps *peers) removeAllowedEncryptionPublicKey(box string) { func (ps *peers) removeAllowedEncryptionPublicKey(box string) {
ps.core.configMutex.RLock() ps.core.config.Mutex.RLock()
defer ps.core.configMutex.RUnlock() defer ps.core.config.Mutex.RUnlock()
for k, v := range ps.core.config.AllowedEncryptionPublicKeys { for k, v := range ps.core.config.Current.AllowedEncryptionPublicKeys {
if v == box { if v == box {
ps.core.config.AllowedEncryptionPublicKeys = ps.core.config.Current.AllowedEncryptionPublicKeys =
append(ps.core.config.AllowedEncryptionPublicKeys[:k], append(ps.core.config.Current.AllowedEncryptionPublicKeys[:k],
ps.core.config.AllowedEncryptionPublicKeys[k+1:]...) ps.core.config.Current.AllowedEncryptionPublicKeys[k+1:]...)
} }
} }
} }
// Gets the whitelist of allowed keys for incoming connections. // Gets the whitelist of allowed keys for incoming connections.
func (ps *peers) getAllowedEncryptionPublicKeys() []string { func (ps *peers) getAllowedEncryptionPublicKeys() []string {
ps.core.configMutex.RLock() ps.core.config.Mutex.RLock()
defer ps.core.configMutex.RUnlock() defer ps.core.config.Mutex.RUnlock()
return ps.core.config.AllowedEncryptionPublicKeys return ps.core.config.Current.AllowedEncryptionPublicKeys
} }
// Atomically gets a map[switchPort]*peer of known peers. // Atomically gets a map[switchPort]*peer of known peers.

View file

@ -31,6 +31,7 @@ import (
"github.com/yggdrasil-network/yggdrasil-go/src/address" "github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto" "github.com/yggdrasil-network/yggdrasil-go/src/crypto"
"github.com/yggdrasil-network/yggdrasil-go/src/tuntap"
"github.com/yggdrasil-network/yggdrasil-go/src/util" "github.com/yggdrasil-network/yggdrasil-go/src/util"
) )
@ -44,8 +45,7 @@ type router struct {
in <-chan []byte // packets we received from the network, link to peer's "out" 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" out func([]byte) // packets we're sending to the network, link to peer's "in"
toRecv chan router_recvPacket // packets to handle via recvPacket() toRecv chan router_recvPacket // packets to handle via recvPacket()
tun tunAdapter // TUN/TAP adapter tun tuntap.TunAdapter // TUN/TAP adapter
adapters []Adapter // Other adapters
recv chan<- []byte // place where the tun pulls received packets from recv chan<- []byte // place where the tun pulls received packets from
send <-chan []byte // place where the tun puts outgoing packets send <-chan []byte // place where the tun puts outgoing packets
reset chan struct{} // signal that coords changed (re-init sessions/dht) reset chan struct{} // signal that coords changed (re-init sessions/dht)
@ -112,11 +112,11 @@ func (r *router) init(core *Core) {
r.reset = make(chan struct{}, 1) r.reset = make(chan struct{}, 1)
r.admin = make(chan func(), 32) r.admin = make(chan func(), 32)
r.nodeinfo.init(r.core) r.nodeinfo.init(r.core)
r.core.configMutex.RLock() r.core.config.Mutex.RLock()
r.nodeinfo.setNodeInfo(r.core.config.NodeInfo, r.core.config.NodeInfoPrivacy) r.nodeinfo.setNodeInfo(r.core.config.Current.NodeInfo, r.core.config.Current.NodeInfoPrivacy)
r.core.configMutex.RUnlock() r.core.config.Mutex.RUnlock()
r.cryptokey.init(r.core) 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. // Starts the mainLoop goroutine.
@ -157,9 +157,9 @@ func (r *router) mainLoop() {
case f := <-r.admin: case f := <-r.admin:
f() f()
case e := <-r.reconfigure: case e := <-r.reconfigure:
r.core.configMutex.RLock() r.core.config.Mutex.RLock()
e <- r.nodeinfo.setNodeInfo(r.core.config.NodeInfo, r.core.config.NodeInfoPrivacy) e <- r.nodeinfo.setNodeInfo(r.core.config.Current.NodeInfo, r.core.config.Current.NodeInfoPrivacy)
r.core.configMutex.RUnlock() r.core.config.Mutex.RUnlock()
} }
} }
} }
@ -320,7 +320,7 @@ func (r *router) sendPacket(bs []byte) {
} }
// Create the ICMPv6 response from it // Create the ICMPv6 response from it
icmpv6Buf, err := r.tun.icmpv6.create_icmpv6_tun( icmpv6Buf, err := r.tun.Icmpv6.Create_ICMPv6_TUN(
bs[8:24], bs[24:40], bs[8:24], bs[24:40],
ipv6.ICMPTypePacketTooBig, 0, ptb) ipv6.ICMPTypePacketTooBig, 0, ptb)
if err == nil { if err == nil {

View file

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

View file

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

View file

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