Break out multicast into a separate package

This commit is contained in:
Neil Alexander 2019-03-28 16:13:14 +00:00
parent 03bc7bbcd6
commit 7ea4e9575e
No known key found for this signature in database
GPG key ID: A02A2019A2BB0944
10 changed files with 103 additions and 71 deletions

View file

@ -209,13 +209,13 @@ func (a *admin) init(c *Core) {
}, 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
for _, v := range a.core.multicast.interfaces() {
intfs = append(intfs, v.Name)
}
return admin_info{"multicast_interfaces": intfs}, nil
})
})*/
a.addHandler("getAllowedEncryptionPublicKeys", []string{}, func(in admin_info) (admin_info, error) {
return admin_info{"allowed_box_pubs": a.getAllowedEncryptionPublicKeys()}, nil
})

View file

@ -40,9 +40,9 @@ type Core struct {
dht dht
admin admin
searches searches
multicast multicast
link link
log *log.Logger
//multicast multicast
link link
log *log.Logger
}
func (c *Core) init() error {
@ -82,7 +82,7 @@ func (c *Core) init() error {
c.searches.init(c)
c.dht.init(c)
c.sessions.init(c)
c.multicast.init(c)
//c.multicast.init(c)
c.peers.init(c)
c.router.init(c)
c.switchTable.init(c) // TODO move before peers? before router?
@ -137,7 +137,7 @@ func (c *Core) UpdateConfig(config *config.NodeConfig) {
c.router.cryptokey.reconfigure,
c.switchTable.reconfigure,
c.link.reconfigure,
c.multicast.reconfigure,
//c.multicast.reconfigure,
}
for _, component := range components {
@ -228,10 +228,10 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
return err
}
if err := c.multicast.start(); err != nil {
/*if err := c.multicast.start(); err != nil {
c.log.Errorln("Failed to start multicast interface")
return err
}
}*/
if err := c.router.tun.Start(c.router.addr, c.router.subnet); err != nil {
c.log.Errorln("Failed to start TUN/TAP")
@ -251,6 +251,11 @@ func (c *Core) Stop() {
c.admin.close()
}
// ListenOn starts a new listener
func (c *Core) ListenTCP(uri string) (*TcpListener, error) {
return c.link.tcp.listen(uri)
}
// Generates a new encryption keypair. The encryption keys are used to
// encrypt traffic and to derive the IPv6 address/subnet of the node.
func (c *Core) NewEncryptionKeys() (*crypto.BoxPubKey, *crypto.BoxPrivKey) {
@ -303,11 +308,20 @@ func (c *Core) SetLogger(log *log.Logger) {
}
// Adds a peer. This should be specified in the peer URI format, i.e.
// tcp://a.b.c.d:e, udp://a.b.c.d:e, socks://a.b.c.d:e/f.g.h.i:j
// tcp://a.b.c.d:e, udp://a.b.c.d:e, socks://a.b.c.d:e/f.g.h.i:j. This adds the
// peer to the peer list, so that they will be called again if the connection
// drops.
func (c *Core) AddPeer(addr string, sintf string) error {
return c.admin.addPeer(addr, sintf)
}
// Calls a peer. This should be specified in the peer URI format, i.e.
// tcp://a.b.c.d:e, udp://a.b.c.d:e, socks://a.b.c.d:e/f.g.h.i:j. This calls the
// peer once, and if the connection drops, it won't be called again.
func (c *Core) CallPeer(addr string, sintf string) error {
return c.link.call(addr, sintf)
}
// Adds an allowed public key. This allow peerings to be restricted only to
// keys that you have selected.
func (c *Core) AddAllowedEncryptionPublicKey(boxStr string) error {

View file

@ -115,7 +115,7 @@ func (c *Core) GetSigPubKeyString() string {
// dummy adapter in place of real TUN - when this call returns a packet, you
// will probably want to give it to the OS to write to TUN.
func (c *Core) RouterRecvPacket() ([]byte, error) {
packet := <-c.router.tun.recv
packet := <-c.router.tun.Recv
return packet, nil
}
@ -125,6 +125,6 @@ func (c *Core) RouterRecvPacket() ([]byte, error) {
// Yggdrasil.
func (c *Core) RouterSendPacket(buf []byte) error {
packet := append(util.GetBytes(), buf[:]...)
c.router.tun.send <- packet
c.router.tun.Send <- packet
return nil
}

View file

@ -1,258 +0,0 @@
package yggdrasil
import (
"context"
"fmt"
"net"
"regexp"
"time"
"golang.org/x/net/ipv6"
)
type multicast struct {
core *Core
reconfigure chan chan error
sock *ipv6.PacketConn
groupAddr string
listeners map[string]*tcpListener
listenPort uint16
}
func (m *multicast) init(core *Core) {
m.core = core
m.reconfigure = make(chan chan error, 1)
m.listeners = make(map[string]*tcpListener)
current, _ := m.core.config.Get()
m.listenPort = current.LinkLocalTCPPort
go func() {
for {
e := <-m.reconfigure
e <- nil
}
}()
m.groupAddr = "[ff02::114]:9001"
// Check if we've been given any expressions
if count := len(m.interfaces()); count != 0 {
m.core.log.Infoln("Found", count, "multicast interface(s)")
}
}
func (m *multicast) start() error {
if len(m.interfaces()) == 0 {
m.core.log.Infoln("Multicast discovery is disabled")
} else {
m.core.log.Infoln("Multicast discovery is enabled")
addr, err := net.ResolveUDPAddr("udp", m.groupAddr)
if err != nil {
return err
}
listenString := fmt.Sprintf("[::]:%v", addr.Port)
lc := net.ListenConfig{
Control: m.multicastReuse,
}
conn, err := lc.ListenPacket(context.Background(), "udp6", listenString)
if err != nil {
return err
}
m.sock = ipv6.NewPacketConn(conn)
if err = m.sock.SetControlMessage(ipv6.FlagDst, true); err != nil {
// Windows can't set this flag, so we need to handle it in other ways
}
go m.multicastStarted()
go m.listen()
go m.announce()
}
return nil
}
func (m *multicast) interfaces() map[string]net.Interface {
// Get interface expressions from config
current, _ := m.core.config.Get()
exprs := current.MulticastInterfaces
// Ask the system for network interfaces
interfaces := make(map[string]net.Interface)
allifaces, err := net.Interfaces()
if err != nil {
panic(err)
}
// Work out which interfaces to announce on
for _, iface := range allifaces {
if iface.Flags&net.FlagUp == 0 {
// Ignore interfaces that are down
continue
}
if iface.Flags&net.FlagMulticast == 0 {
// Ignore non-multicast interfaces
continue
}
if iface.Flags&net.FlagPointToPoint != 0 {
// Ignore point-to-point interfaces
continue
}
for _, expr := range exprs {
// Compile each regular expression
e, err := regexp.Compile(expr)
if err != nil {
panic(err)
}
// Does the interface match the regular expression? Store it if so
if e.MatchString(iface.Name) {
interfaces[iface.Name] = iface
}
}
}
return interfaces
}
func (m *multicast) announce() {
groupAddr, err := net.ResolveUDPAddr("udp6", m.groupAddr)
if err != nil {
panic(err)
}
destAddr, err := net.ResolveUDPAddr("udp6", m.groupAddr)
if err != nil {
panic(err)
}
for {
interfaces := m.interfaces()
// There might be interfaces that we configured listeners for but are no
// longer up - if that's the case then we should stop the listeners
for name, listener := range m.listeners {
// Prepare our stop function!
stop := func() {
listener.stop <- true
delete(m.listeners, name)
m.core.log.Debugln("No longer multicasting on", name)
}
// If the interface is no longer visible on the system then stop the
// listener, as another one will be started further down
if _, ok := interfaces[name]; !ok {
stop()
continue
}
// It's possible that the link-local listener address has changed so if
// that is the case then we should clean up the interface listener
found := false
listenaddr, err := net.ResolveTCPAddr("tcp6", listener.listener.Addr().String())
if err != nil {
stop()
continue
}
// Find the interface that matches the listener
if intf, err := net.InterfaceByName(name); err == nil {
if addrs, err := intf.Addrs(); err == nil {
// Loop through the addresses attached to that listener and see if any
// of them match the current address of the listener
for _, addr := range addrs {
if ip, _, err := net.ParseCIDR(addr.String()); err == nil {
// Does the interface address match our listener address?
if ip.Equal(listenaddr.IP) {
found = true
break
}
}
}
}
}
// If the address has not been found on the adapter then we should stop
// and clean up the TCP listener. A new one will be created below if a
// suitable link-local address is found
if !found {
stop()
}
}
// Now that we have a list of valid interfaces from the operating system,
// we can start checking if we can send multicasts on them
for _, iface := range interfaces {
// Find interface addresses
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
addrIP, _, _ := net.ParseCIDR(addr.String())
// Ignore IPv4 addresses
if addrIP.To4() != nil {
continue
}
// Ignore non-link-local addresses
if !addrIP.IsLinkLocalUnicast() {
continue
}
// Join the multicast group
m.sock.JoinGroup(&iface, groupAddr)
// Try and see if we already have a TCP listener for this interface
var listener *tcpListener
if l, ok := m.listeners[iface.Name]; !ok || l.listener == nil {
// No listener was found - let's create one
listenaddr := fmt.Sprintf("[%s%%%s]:%d", addrIP, iface.Name, m.listenPort)
if li, err := m.core.link.tcp.listen(listenaddr); err == nil {
m.core.log.Debugln("Started multicasting on", iface.Name)
// Store the listener so that we can stop it later if needed
m.listeners[iface.Name] = li
listener = li
} else {
m.core.log.Warnln("Not multicasting on", iface.Name, "due to error:", err)
}
} else {
// An existing listener was found
listener = m.listeners[iface.Name]
}
// Make sure nothing above failed for some reason
if listener == nil {
continue
}
// Get the listener details and construct the multicast beacon
lladdr := listener.listener.Addr().String()
if a, err := net.ResolveTCPAddr("tcp6", lladdr); err == nil {
a.Zone = ""
destAddr.Zone = iface.Name
msg := []byte(a.String())
m.sock.WriteTo(msg, nil, destAddr)
}
break
}
}
time.Sleep(time.Second * 15)
}
}
func (m *multicast) listen() {
groupAddr, err := net.ResolveUDPAddr("udp6", m.groupAddr)
if err != nil {
panic(err)
}
bs := make([]byte, 2048)
for {
nBytes, rcm, fromAddr, err := m.sock.ReadFrom(bs)
if err != nil {
panic(err)
}
if rcm != nil {
// Windows can't set the flag needed to return a non-nil value here
// So only make these checks if we get something useful back
// TODO? Skip them always, I'm not sure if they're really needed...
if !rcm.Dst.IsLinkLocalMulticast() {
continue
}
if !rcm.Dst.Equal(groupAddr.IP) {
continue
}
}
anAddr := string(bs[:nBytes])
addr, err := net.ResolveTCPAddr("tcp6", anAddr)
if err != nil {
continue
}
from := fromAddr.(*net.UDPAddr)
if addr.IP.String() != from.IP.String() {
continue
}
addr.Zone = ""
if err := m.core.link.call("tcp://"+addr.String(), from.Zone); err != nil {
m.core.log.Debugln("Call from multicast failed:", err)
}
}
}

View file

@ -1,72 +0,0 @@
// +build darwin
package yggdrasil
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation
#import <Foundation/Foundation.h>
NSNetServiceBrowser *serviceBrowser;
void StartAWDLBrowsing() {
if (serviceBrowser == nil) {
serviceBrowser = [[NSNetServiceBrowser alloc] init];
serviceBrowser.includesPeerToPeer = YES;
}
[serviceBrowser searchForServicesOfType:@"_yggdrasil._tcp" inDomain:@""];
}
void StopAWDLBrowsing() {
if (serviceBrowser == nil) {
return;
}
[serviceBrowser stop];
}
*/
import "C"
import (
"syscall"
"time"
"golang.org/x/sys/unix"
)
var awdlGoroutineStarted bool
func (m *multicast) multicastStarted() {
if awdlGoroutineStarted {
return
}
m.core.log.Infoln("Multicast discovery will wake up AWDL if required")
awdlGoroutineStarted = true
for {
C.StopAWDLBrowsing()
for _, intf := range m.interfaces() {
if intf.Name == "awdl0" {
C.StartAWDLBrowsing()
break
}
}
time.Sleep(time.Minute)
}
}
func (m *multicast) multicastReuse(network string, address string, c syscall.RawConn) error {
var control error
var reuseport error
var recvanyif error
control = c.Control(func(fd uintptr) {
reuseport = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
// sys/socket.h: #define SO_RECV_ANYIF 0x1104
recvanyif = unix.SetsockoptInt(int(fd), syscall.SOL_SOCKET, 0x1104, 1)
})
switch {
case reuseport != nil:
return reuseport
case recvanyif != nil:
return recvanyif
default:
return control
}
}

View file

@ -1,13 +0,0 @@
// +build !linux,!darwin,!netbsd,!freebsd,!openbsd,!dragonflybsd,!windows
package yggdrasil
import "syscall"
func (m *multicast) multicastStarted() {
}
func (m *multicast) multicastReuse(network string, address string, c syscall.RawConn) error {
return nil
}

View file

@ -1,26 +0,0 @@
// +build linux netbsd freebsd openbsd dragonflybsd
package yggdrasil
import "syscall"
import "golang.org/x/sys/unix"
func (m *multicast) multicastStarted() {
}
func (m *multicast) multicastReuse(network string, address string, c syscall.RawConn) error {
var control error
var reuseport error
control = c.Control(func(fd uintptr) {
reuseport = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
})
switch {
case reuseport != nil:
return reuseport
default:
return control
}
}

View file

@ -1,26 +0,0 @@
// +build windows
package yggdrasil
import "syscall"
import "golang.org/x/sys/windows"
func (m *multicast) multicastStarted() {
}
func (m *multicast) multicastReuse(network string, address string, c syscall.RawConn) error {
var control error
var reuseaddr error
control = c.Control(func(fd uintptr) {
reuseaddr = windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
})
switch {
case reuseaddr != nil:
return reuseaddr
default:
return control
}
}

View file

@ -36,14 +36,14 @@ type tcp struct {
link *link
reconfigure chan chan error
mutex sync.Mutex // Protecting the below
listeners map[string]*tcpListener
listeners map[string]*TcpListener
calls map[string]struct{}
conns map[linkInfo](chan struct{})
}
type tcpListener struct {
listener net.Listener
stop chan bool
type TcpListener struct {
Listener net.Listener
Stop chan bool
}
// Wrapper function to set additional options for specific connection types.
@ -64,7 +64,7 @@ func (t *tcp) getAddr() *net.TCPAddr {
t.mutex.Lock()
defer t.mutex.Unlock()
for _, l := range t.listeners {
return l.listener.Addr().(*net.TCPAddr)
return l.Listener.Addr().(*net.TCPAddr)
}
return nil
}
@ -76,7 +76,7 @@ func (t *tcp) init(l *link) error {
t.mutex.Lock()
t.calls = make(map[string]struct{})
t.conns = make(map[linkInfo](chan struct{}))
t.listeners = make(map[string]*tcpListener)
t.listeners = make(map[string]*TcpListener)
t.mutex.Unlock()
go func() {
@ -103,7 +103,7 @@ func (t *tcp) init(l *link) error {
t.mutex.Lock()
if listener, ok := t.listeners[d[6:]]; ok {
t.mutex.Unlock()
listener.stop <- true
listener.Stop <- true
} else {
t.mutex.Unlock()
}
@ -129,7 +129,7 @@ func (t *tcp) init(l *link) error {
return nil
}
func (t *tcp) listen(listenaddr string) (*tcpListener, error) {
func (t *tcp) listen(listenaddr string) (*TcpListener, error) {
var err error
ctx := context.Background()
@ -138,9 +138,9 @@ func (t *tcp) listen(listenaddr string) (*tcpListener, error) {
}
listener, err := lc.Listen(ctx, "tcp", listenaddr)
if err == nil {
l := tcpListener{
listener: listener,
stop: make(chan bool),
l := TcpListener{
Listener: listener,
Stop: make(chan bool),
}
go t.listener(&l, listenaddr)
return &l, nil
@ -150,7 +150,7 @@ func (t *tcp) listen(listenaddr string) (*tcpListener, error) {
}
// Runs the listener, which spawns off goroutines for incoming connections.
func (t *tcp) listener(l *tcpListener, listenaddr string) {
func (t *tcp) listener(l *TcpListener, listenaddr string) {
if l == nil {
return
}
@ -158,7 +158,7 @@ func (t *tcp) listener(l *tcpListener, listenaddr string) {
t.mutex.Lock()
if _, isIn := t.listeners[listenaddr]; isIn {
t.mutex.Unlock()
l.listener.Close()
l.Listener.Close()
return
} else {
t.listeners[listenaddr] = l
@ -167,20 +167,20 @@ func (t *tcp) listener(l *tcpListener, listenaddr string) {
// And here we go!
accepted := make(chan bool)
defer func() {
t.link.core.log.Infoln("Stopping TCP listener on:", l.listener.Addr().String())
l.listener.Close()
t.link.core.log.Infoln("Stopping TCP listener on:", l.Listener.Addr().String())
l.Listener.Close()
t.mutex.Lock()
delete(t.listeners, listenaddr)
t.mutex.Unlock()
}()
t.link.core.log.Infoln("Listening for TCP on:", l.listener.Addr().String())
t.link.core.log.Infoln("Listening for TCP on:", l.Listener.Addr().String())
for {
var sock net.Conn
var err error
// Listen in a separate goroutine, as that way it does not block us from
// receiving "stop" events
go func() {
sock, err = l.listener.Accept()
sock, err = l.Listener.Accept()
accepted <- true
}()
// Wait for either an accepted connection, or a message telling us to stop
@ -192,7 +192,7 @@ func (t *tcp) listener(l *tcpListener, listenaddr string) {
return
}
go t.handler(sock, true, nil)
case <-l.stop:
case <-l.Stop:
return
}
}