5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-12-23 12:15:39 +00:00

Merge pull request #87 from neilalexander/config

Update configuration names and update multicast behaviour
This commit is contained in:
Arceliar 2018-05-23 13:08:34 -05:00 committed by GitHub
commit 9e5964dcd4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 297 additions and 196 deletions

View File

@ -54,11 +54,17 @@ cat > /tmp/$PKGNAME/debian/docs << EOF
Please see https://github.com/Arceliar/yggdrasil-go/
EOF
cat > /tmp/$PKGNAME/debian/install << EOF
usr/bin/yggdrasil usr/bin/yggdrasilctl usr/bin
usr/bin/yggdrasil usr/bin
usr/bin/yggdrasilctl usr/bin
etc/systemd/system/*.service etc/systemd/system
EOF
cat > /tmp/$PKGNAME/debian/postinst << EOF
#!/bin/sh
if [ -f /etc/yggdrasil.conf ];
then
cp /etc/yggdrasil.conf /etc/yggdrasil.conf.pre-upgrade
./yggdrasil -useconffile /etc/yggdrasil.conf.pre-upgrade -normaliseconf > /etc/yggdrasil.conf;
fi
systemctl enable yggdrasil
systemctl start yggdrasil
EOF

View File

@ -48,16 +48,16 @@ func (n *Node) startPeers() {
func linkNodes(m, n *Node) {
// Don't allow duplicates
if m.core.DEBUG_getPeers().DEBUG_hasPeer(n.core.DEBUG_getSigPub()) {
if m.core.DEBUG_getPeers().DEBUG_hasPeer(n.core.DEBUG_getSigningPublicKey()) {
return
}
// Create peers
// Buffering reduces packet loss in the sim
// This slightly speeds up testing (fewer delays before retrying a ping)
p := m.core.DEBUG_getPeers().DEBUG_newPeer(n.core.DEBUG_getBoxPub(),
n.core.DEBUG_getSigPub())
q := n.core.DEBUG_getPeers().DEBUG_newPeer(m.core.DEBUG_getBoxPub(),
m.core.DEBUG_getSigPub())
p := m.core.DEBUG_getPeers().DEBUG_newPeer(n.core.DEBUG_getEncryptionPublicKey(),
n.core.DEBUG_getSigningPublicKey())
q := n.core.DEBUG_getPeers().DEBUG_newPeer(m.core.DEBUG_getEncryptionPublicKey(),
m.core.DEBUG_getSigningPublicKey())
DEBUG_simLinkPeers(p, q)
return
}
@ -141,7 +141,7 @@ func startNetwork(store map[[32]byte]*Node) {
func getKeyedStore(store map[int]*Node) map[[32]byte]*Node {
newStore := make(map[[32]byte]*Node)
for _, node := range store {
newStore[node.core.DEBUG_getSigPub()] = node
newStore[node.core.DEBUG_getSigningPublicKey()] = node
}
return newStore
}
@ -257,7 +257,7 @@ func pingNodes(store map[[32]byte]*Node) {
count++
//if count > 16 { break }
fmt.Printf("Sending packets from node %d/%d (%d)\n", count, nNodes, source.index)
sourceKey := source.core.DEBUG_getBoxPub()
sourceKey := source.core.DEBUG_getEncryptionPublicKey()
payload := sourceKey[:]
sourceAddr := source.core.DEBUG_getAddr()[:]
sendTo := func(bs []byte, destAddr []byte) {
@ -329,7 +329,7 @@ func pingBench(store map[[32]byte]*Node) {
return packet
}
for _, dest := range store {
key := dest.core.DEBUG_getBoxPub()
key := dest.core.DEBUG_getEncryptionPublicKey()
loc := dest.core.DEBUG_getLocator()
coords := loc.DEBUG_getCoords()
ping := getPing(key, coords)

View File

@ -173,11 +173,11 @@ func (a *admin) init(c *Core, listenaddr string) {
}, nil
}
})
a.addHandler("getAllowedBoxPubs", []string{}, func(in admin_info) (admin_info, error) {
return admin_info{"allowed_box_pubs": a.getAllowedBoxPubs()}, nil
a.addHandler("getAllowedEncryptionPublicKeys", []string{}, func(in admin_info) (admin_info, error) {
return admin_info{"allowed_box_pubs": a.getAllowedEncryptionPublicKeys()}, nil
})
a.addHandler("addAllowedBoxPub", []string{"box_pub_key"}, func(in admin_info) (admin_info, error) {
if a.addAllowedBoxPub(in["box_pub_key"].(string)) == nil {
a.addHandler("addAllowedEncryptionPublicKey", []string{"box_pub_key"}, func(in admin_info) (admin_info, error) {
if a.addAllowedEncryptionPublicKey(in["box_pub_key"].(string)) == nil {
return admin_info{
"added": []string{
in["box_pub_key"].(string),
@ -191,8 +191,8 @@ func (a *admin) init(c *Core, listenaddr string) {
}, errors.New("Failed to add allowed box pub key")
}
})
a.addHandler("removeAllowedBoxPub", []string{"box_pub_key"}, func(in admin_info) (admin_info, error) {
if a.removeAllowedBoxPub(in["box_pub_key"].(string)) == nil {
a.addHandler("removeAllowedEncryptionPublicKey", []string{"box_pub_key"}, func(in admin_info) (admin_info, error) {
if a.removeAllowedEncryptionPublicKey(in["box_pub_key"].(string)) == nil {
return admin_info{
"removed": []string{
in["box_pub_key"].(string),
@ -514,8 +514,8 @@ func (a *admin) getData_getSessions() []admin_nodeInfo {
return infos
}
func (a *admin) getAllowedBoxPubs() []string {
pubs := a.core.peers.getAllowedBoxPubs()
func (a *admin) getAllowedEncryptionPublicKeys() []string {
pubs := a.core.peers.getAllowedEncryptionPublicKeys()
var out []string
for _, pub := range pubs {
out = append(out, hex.EncodeToString(pub[:]))
@ -523,22 +523,22 @@ func (a *admin) getAllowedBoxPubs() []string {
return out
}
func (a *admin) addAllowedBoxPub(bstr string) (err error) {
func (a *admin) addAllowedEncryptionPublicKey(bstr string) (err error) {
boxBytes, err := hex.DecodeString(bstr)
if err == nil {
var box boxPubKey
copy(box[:], boxBytes)
a.core.peers.addAllowedBoxPub(&box)
a.core.peers.addAllowedEncryptionPublicKey(&box)
}
return
}
func (a *admin) removeAllowedBoxPub(bstr string) (err error) {
func (a *admin) removeAllowedEncryptionPublicKey(bstr string) (err error) {
boxBytes, err := hex.DecodeString(bstr)
if err == nil {
var box boxPubKey
copy(box[:], boxBytes)
a.core.peers.removeAllowedBoxPub(&box)
a.core.peers.removeAllowedEncryptionPublicKey(&box)
}
return
}

View File

@ -2,24 +2,23 @@ package config
// NodeConfig defines all configuration values needed to run a signle yggdrasil node
type NodeConfig struct {
Listen string `comment:"Listen address for peer connections (default is to listen for all\nconnections over IPv4 and IPv6)"`
AdminListen string `comment:"Listen address for admin connections (default is to listen only\nfor local connections)"`
Peers []string `comment:"List of connection strings for static peers (i.e. tcp://a.b.c.d:e)"`
AllowedBoxPubs []string `comment:"List of peer BoxPubs to allow UDP incoming TCP connections from\n(if left empty/undefined then connections will be allowed by default)"`
BoxPub string `comment:"Your public encryption key (your peers may ask you for this to put\ninto their AllowedBoxPubs configuration)"`
BoxPriv string `comment:"Your private encryption key (do not share this with anyone!)"`
SigPub string `comment:"Your public signing key"`
SigPriv string `comment:"Your private signing key (do not share this with anyone!)"`
Multicast bool `comment:"Enable or disable automatic peer discovery on the same LAN using multicast"`
LinkLocal string `comment:"Regex for which interfaces multicast peer discovery should be enabled on"`
IfName string `comment:"Local network interface name for TUN/TAP adapter, or \"auto\", or \"none\""`
IfTAPMode bool `comment:"Set local network interface to TAP mode rather than TUN mode (if supported\nby your platform, option will be ignored if not)"`
IfMTU int `comment:"Maximux Transmission Unit (MTU) size for your local network interface"`
Net NetConfig `comment:"Extended options for interoperability with other networks"`
Listen string `comment:"Listen address for peer connections. Default is to listen for all\nUDP and TCP connections over IPv4 and IPv6."`
AdminListen string `comment:"Listen address for admin connections Default is to listen for local\nconnections only on TCP port 9001."`
Peers []string `comment:"List of connection strings for static peers in URI format, i.e.\ntcp://a.b.c.d:e, udp://a.b.c.d:e, socks://a.b.c.d:e/f.g.h.i:j etc."`
AllowedEncryptionPublicKeys []string `comment:"List of peer encryption public keys to allow incoming/outgoing UDP\nor incoming TCP connections from. If left empty/undefined then all\nconnections will be allowed by default."`
EncryptionPublicKey string `comment:"Your public encryption key. Your peers may ask you for this to put\ninto their AllowedEncryptionPublicKeys configuration."`
EncryptionPrivateKey string `comment:"Your private encryption key. DO NOT share this with anyone!"`
SigningPublicKey string `comment:"Your public signing key. You should not ordinarily need to share\nthis with anyone."`
SigningPrivateKey string `comment:"Your private signing key. DO NOT share this with anyone!"`
MulticastInterfaces []string `comment:"Regular expressions for which interfaces multicast peer discovery\nshould be enabled on. If none specified, multicast peer discovery is\ndisabled. The default value is .* which uses all interfaces."`
IfName string `comment:"Local network interface name for TUN/TAP adapter, or \"auto\" to select\nan interface automatically, or \"none\" to run without TUN/TAP."`
IfTAPMode bool `comment:"Set local network interface to TAP mode rather than TUN mode if\nsupported by your platform - option will be ignored if not."`
IfMTU int `comment:"Maximux Transmission Unit (MTU) size for your local TUN/TAP interface.\nDefault is the largest supported size for your platform. The lowest\npossible value is 1280."`
Net NetConfig `comment:"Extended options for connecting to peers over other networks."`
}
// NetConfig defines network/proxy related configuration values
type NetConfig struct {
Tor TorConfig `comment:"Experimental options for configuring peerings over Tor"`
I2P I2PConfig `comment:"Experimental options for configuring peerings over I2P"`
Tor TorConfig `comment:"Experimental options for configuring peerings over Tor."`
I2P I2PConfig `comment:"Experimental options for configuring peerings over I2P."`
}

View File

@ -19,10 +19,11 @@ type Core struct {
tun tunDevice
admin admin
searches searches
multicast multicast
tcp *tcpInterface
udp *udpInterface
log *log.Logger
ifceExpr *regexp.Regexp // the zone of link-local IPv6 peers must match this
ifceExpr []*regexp.Regexp // the zone of link-local IPv6 peers must match this
}
func (c *Core) Init() {
@ -49,6 +50,7 @@ func (c *Core) init(bpub *boxPubKey,
c.searches.init(c)
c.dht.init(c)
c.sessions.init(c)
c.multicast.init(c)
c.peers.init(c)
c.router.init(c)
c.switchTable.init(c, c.sigPub) // TODO move before peers? before router?

View File

@ -17,11 +17,11 @@ import "regexp"
// Core
func (c *Core) DEBUG_getSigPub() sigPubKey {
func (c *Core) DEBUG_getSigningPublicKey() sigPubKey {
return (sigPubKey)(c.sigPub)
}
func (c *Core) DEBUG_getBoxPub() boxPubKey {
func (c *Core) DEBUG_getEncryptionPublicKey() boxPubKey {
return (boxPubKey)(c.boxPub)
}
@ -387,6 +387,13 @@ func (c *Core) DEBUG_setupAndStartAdminInterface(addrport string) {
c.admin = a
}
func (c *Core) DEBUG_setupAndStartMulticastInterface() {
m := multicast{}
m.init(c)
c.multicast = m
m.start()
}
////////////////////////////////////////////////////////////////////////////////
func (c *Core) DEBUG_setLogger(log *log.Logger) {
@ -394,11 +401,11 @@ func (c *Core) DEBUG_setLogger(log *log.Logger) {
}
func (c *Core) DEBUG_setIfceExpr(expr *regexp.Regexp) {
c.ifceExpr = expr
c.ifceExpr = append(c.ifceExpr, expr)
}
func (c *Core) DEBUG_addAllowedBoxPub(boxStr string) {
err := c.admin.addAllowedBoxPub(boxStr)
func (c *Core) DEBUG_addAllowedEncryptionPublicKey(boxStr string) {
err := c.admin.addAllowedEncryptionPublicKey(boxStr)
if err != nil {
panic(err)
}

157
src/yggdrasil/multicast.go Normal file
View File

@ -0,0 +1,157 @@
package yggdrasil
import "net"
import "time"
import "fmt"
import "golang.org/x/net/ipv6"
type multicast struct {
core *Core
sock *ipv6.PacketConn
groupAddr string
interfaces []net.Interface
}
func (m *multicast) init(core *Core) {
m.core = core
m.groupAddr = "[ff02::114]:9001"
// Ask the system for network interfaces
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 m.core.ifceExpr {
if expr.MatchString(iface.Name) {
m.interfaces = append(m.interfaces, iface)
}
}
}
m.core.log.Println("Found", len(m.interfaces), "multicast interface(s)")
}
func (m *multicast) start() {
if len(m.core.ifceExpr) == 0 {
m.core.log.Println("Multicast discovery is disabled")
} else {
m.core.log.Println("Multicast discovery is enabled")
addr, err := net.ResolveUDPAddr("udp", m.groupAddr)
if err != nil {
panic(err)
}
listenString := fmt.Sprintf("[::]:%v", addr.Port)
conn, err := net.ListenPacket("udp6", listenString)
if err != nil {
panic(err)
}
//defer conn.Close() // Let it close on its own when the application exits
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
//panic(err)
}
go m.listen()
go m.announce()
}
}
func (m *multicast) announce() {
groupAddr, err := net.ResolveUDPAddr("udp6", m.groupAddr)
if err != nil {
panic(err)
}
var anAddr net.TCPAddr
myAddr := m.core.DEBUG_getGlobalTCPAddr()
anAddr.Port = myAddr.Port
destAddr, err := net.ResolveUDPAddr("udp6", m.groupAddr)
if err != nil {
panic(err)
}
for {
for _, iface := range m.interfaces {
m.sock.JoinGroup(&iface, groupAddr)
//err := n.sock.JoinGroup(&iface, groupAddr)
//if err != nil { panic(err) }
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
addrIP, _, _ := net.ParseCIDR(addr.String())
if addrIP.To4() != nil {
continue
} // IPv6 only
if !addrIP.IsLinkLocalUnicast() {
continue
}
anAddr.IP = addrIP
anAddr.Zone = iface.Name
destAddr.Zone = iface.Name
msg := []byte(anAddr.String())
m.sock.WriteTo(msg, nil, destAddr)
break
}
time.Sleep(time.Second)
}
time.Sleep(time.Second)
}
}
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 { continue } // wat
//fmt.Println("DEBUG:", "packet from:", fromAddr.String())
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 {
panic(err)
continue
} // Panic for testing, remove later
from := fromAddr.(*net.UDPAddr)
//fmt.Println("DEBUG:", "heard:", addr.IP.String(), "from:", from.IP.String())
if addr.IP.String() != from.IP.String() {
continue
}
addr.Zone = from.Zone
saddr := addr.String()
//if _, isIn := n.peers[saddr]; isIn { continue }
//n.peers[saddr] = struct{}{}
m.core.DEBUG_addTCPConn(saddr)
//fmt.Println("DEBUG:", "added multicast peer:", saddr)
}
}

View File

@ -34,8 +34,8 @@ type peers struct {
mutex sync.Mutex // Synchronize writes to atomic
ports atomic.Value //map[Port]*peer, use CoW semantics
//ports map[Port]*peer
authMutex sync.RWMutex
allowedBoxPubs map[boxPubKey]struct{}
authMutex sync.RWMutex
allowedEncryptionPublicKeys map[boxPubKey]struct{}
}
func (ps *peers) init(c *Core) {
@ -43,33 +43,33 @@ func (ps *peers) init(c *Core) {
defer ps.mutex.Unlock()
ps.putPorts(make(map[switchPort]*peer))
ps.core = c
ps.allowedBoxPubs = make(map[boxPubKey]struct{})
ps.allowedEncryptionPublicKeys = make(map[boxPubKey]struct{})
}
func (ps *peers) isAllowedBoxPub(box *boxPubKey) bool {
func (ps *peers) isAllowedEncryptionPublicKey(box *boxPubKey) bool {
ps.authMutex.RLock()
defer ps.authMutex.RUnlock()
_, isIn := ps.allowedBoxPubs[*box]
return isIn || len(ps.allowedBoxPubs) == 0
_, isIn := ps.allowedEncryptionPublicKeys[*box]
return isIn || len(ps.allowedEncryptionPublicKeys) == 0
}
func (ps *peers) addAllowedBoxPub(box *boxPubKey) {
func (ps *peers) addAllowedEncryptionPublicKey(box *boxPubKey) {
ps.authMutex.Lock()
defer ps.authMutex.Unlock()
ps.allowedBoxPubs[*box] = struct{}{}
ps.allowedEncryptionPublicKeys[*box] = struct{}{}
}
func (ps *peers) removeAllowedBoxPub(box *boxPubKey) {
func (ps *peers) removeAllowedEncryptionPublicKey(box *boxPubKey) {
ps.authMutex.Lock()
defer ps.authMutex.Unlock()
delete(ps.allowedBoxPubs, *box)
delete(ps.allowedEncryptionPublicKeys, *box)
}
func (ps *peers) getAllowedBoxPubs() []boxPubKey {
func (ps *peers) getAllowedEncryptionPublicKeys() []boxPubKey {
ps.authMutex.RLock()
defer ps.authMutex.RUnlock()
keys := make([]boxPubKey, 0, len(ps.allowedBoxPubs))
for key := range ps.allowedBoxPubs {
keys := make([]boxPubKey, 0, len(ps.allowedEncryptionPublicKeys))
for key := range ps.allowedEncryptionPublicKeys {
keys = append(keys, key)
}
return keys

View File

@ -151,7 +151,7 @@ func (iface *tcpInterface) handler(sock net.Conn, incoming bool) {
return
}
// Check if we're authorized to connect to this key / IP
if incoming && !iface.core.peers.isAllowedBoxPub(&info.box) {
if incoming && !iface.core.peers.isAllowedEncryptionPublicKey(&info.box) {
// Allow unauthorized peers if they're link-local
raddrStr, _, _ := net.SplitHostPort(sock.RemoteAddr().String())
raddr := net.ParseIP(raddrStr)

View File

@ -206,7 +206,7 @@ func (iface *udpInterface) handleKeys(msg []byte, addr connAddr) {
udpAddr := addr.toUDPAddr()
// Check if we're authorized to connect to this key / IP
// TODO monitor and always allow outgoing connections
if !iface.core.peers.isAllowedBoxPub(&ks.box) {
if !iface.core.peers.isAllowedEncryptionPublicKey(&ks.box) {
// Allow unauthorized peers if they're link-local
if !udpAddr.IP.IsLinkLocalUnicast() {
return
@ -341,11 +341,17 @@ func (iface *udpInterface) reader() {
if them.isValid() {
continue
}
if udpAddr.IP.IsLinkLocalUnicast() &&
!iface.core.ifceExpr.MatchString(udpAddr.Zone) {
continue
if udpAddr.IP.IsLinkLocalUnicast() {
if len(iface.core.ifceExpr) == 0 {
break
}
for _, expr := range iface.core.ifceExpr {
if expr.MatchString(udpAddr.Zone) {
iface.handleKeys(msg, addr)
break
}
}
}
iface.handleKeys(msg, addr)
case udp_isClose(msg):
iface.handleClose(msg, addr)
default:

View File

@ -17,8 +17,6 @@ import "net/http"
import "log"
import "runtime"
import "golang.org/x/net/ipv6"
import "yggdrasil"
import "yggdrasil/config"
@ -31,33 +29,27 @@ type Core = yggdrasil.Core
type node struct {
core Core
sock *ipv6.PacketConn
}
func (n *node) init(cfg *nodeConfig, logger *log.Logger) {
boxPub, err := hex.DecodeString(cfg.BoxPub)
boxPub, err := hex.DecodeString(cfg.EncryptionPublicKey)
if err != nil {
panic(err)
}
boxPriv, err := hex.DecodeString(cfg.BoxPriv)
boxPriv, err := hex.DecodeString(cfg.EncryptionPrivateKey)
if err != nil {
panic(err)
}
sigPub, err := hex.DecodeString(cfg.SigPub)
sigPub, err := hex.DecodeString(cfg.SigningPublicKey)
if err != nil {
panic(err)
}
sigPriv, err := hex.DecodeString(cfg.SigPriv)
sigPriv, err := hex.DecodeString(cfg.SigningPrivateKey)
if err != nil {
panic(err)
}
n.core.DEBUG_init(boxPub, boxPriv, sigPub, sigPriv)
n.core.DEBUG_setLogger(logger)
ifceExpr, err := regexp.Compile(cfg.LinkLocal)
if err != nil {
panic(err)
}
n.core.DEBUG_setIfceExpr(ifceExpr)
logger.Println("Starting interface...")
n.core.DEBUG_setupAndStartGlobalTCPInterface(cfg.Listen) // Listen for peers on TCP
@ -66,9 +58,17 @@ func (n *node) init(cfg *nodeConfig, logger *log.Logger) {
logger.Println("Starting admin socket...")
n.core.DEBUG_setupAndStartAdminInterface(cfg.AdminListen)
logger.Println("Started admin socket")
for _, pBoxStr := range cfg.AllowedBoxPubs {
n.core.DEBUG_addAllowedBoxPub(pBoxStr)
for _, pBoxStr := range cfg.AllowedEncryptionPublicKeys {
n.core.DEBUG_addAllowedEncryptionPublicKey(pBoxStr)
}
for _, ll := range cfg.MulticastInterfaces {
ifceExpr, err := regexp.Compile(ll)
if err != nil {
panic(err)
}
n.core.DEBUG_setIfceExpr(ifceExpr)
}
n.core.DEBUG_setupAndStartMulticastInterface()
go func() {
if len(cfg.Peers) == 0 {
@ -96,14 +96,13 @@ func generateConfig(isAutoconf bool) *nodeConfig {
cfg.Listen = fmt.Sprintf("[::]:%d", r1.Intn(65534-32768)+32768)
}
cfg.AdminListen = "[::1]:9001"
cfg.BoxPub = hex.EncodeToString(bpub[:])
cfg.BoxPriv = hex.EncodeToString(bpriv[:])
cfg.SigPub = hex.EncodeToString(spub[:])
cfg.SigPriv = hex.EncodeToString(spriv[:])
cfg.EncryptionPublicKey = hex.EncodeToString(bpub[:])
cfg.EncryptionPrivateKey = hex.EncodeToString(bpriv[:])
cfg.SigningPublicKey = hex.EncodeToString(spub[:])
cfg.SigningPrivateKey = hex.EncodeToString(spriv[:])
cfg.Peers = []string{}
cfg.AllowedBoxPubs = []string{}
cfg.Multicast = true
cfg.LinkLocal = ""
cfg.AllowedEncryptionPublicKeys = []string{}
cfg.MulticastInterfaces = []string{".*"}
cfg.IfName = core.DEBUG_GetTUNDefaultIfName()
cfg.IfMTU = core.DEBUG_GetTUNDefaultIfMTU()
cfg.IfTAPMode = core.DEBUG_GetTUNDefaultIfTAPMode()
@ -120,102 +119,11 @@ func doGenconf() string {
return string(bs)
}
var multicastAddr = "[ff02::114]:9001"
func (n *node) listen() {
groupAddr, err := net.ResolveUDPAddr("udp6", multicastAddr)
if err != nil {
panic(err)
}
bs := make([]byte, 2048)
for {
nBytes, rcm, fromAddr, err := n.sock.ReadFrom(bs)
if err != nil {
panic(err)
}
//if rcm == nil { continue } // wat
//fmt.Println("DEBUG:", "packet from:", fromAddr.String())
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 {
panic(err)
continue
} // Panic for testing, remove later
from := fromAddr.(*net.UDPAddr)
//fmt.Println("DEBUG:", "heard:", addr.IP.String(), "from:", from.IP.String())
if addr.IP.String() != from.IP.String() {
continue
}
addr.Zone = from.Zone
saddr := addr.String()
//if _, isIn := n.peers[saddr]; isIn { continue }
//n.peers[saddr] = struct{}{}
n.core.DEBUG_addTCPConn(saddr)
//fmt.Println("DEBUG:", "added multicast peer:", saddr)
}
}
func (n *node) announce() {
groupAddr, err := net.ResolveUDPAddr("udp6", multicastAddr)
if err != nil {
panic(err)
}
var anAddr net.TCPAddr
myAddr := n.core.DEBUG_getGlobalTCPAddr()
anAddr.Port = myAddr.Port
destAddr, err := net.ResolveUDPAddr("udp6", multicastAddr)
if err != nil {
panic(err)
}
for {
ifaces, err := net.Interfaces()
if err != nil {
panic(err)
}
for _, iface := range ifaces {
n.sock.JoinGroup(&iface, groupAddr)
//err := n.sock.JoinGroup(&iface, groupAddr)
//if err != nil { panic(err) }
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
addrIP, _, _ := net.ParseCIDR(addr.String())
if addrIP.To4() != nil {
continue
} // IPv6 only
if !addrIP.IsLinkLocalUnicast() {
continue
}
anAddr.IP = addrIP
anAddr.Zone = iface.Name
destAddr.Zone = iface.Name
msg := []byte(anAddr.String())
n.sock.WriteTo(msg, nil, destAddr)
break
}
time.Sleep(time.Second)
}
time.Sleep(time.Second)
}
}
var pprof = flag.Bool("pprof", false, "Run pprof, see http://localhost:6060/debug/pprof/")
var genconf = flag.Bool("genconf", false, "print a new config to stdout")
var useconf = flag.Bool("useconf", false, "read config from stdin")
var useconffile = flag.String("useconffile", "", "read config from specified file path")
var normaliseconf = flag.Bool("normaliseconf", false, "use in combination with either -useconf or -useconffile, outputs your configuration normalised")
var autoconf = flag.Bool("autoconf", false, "automatic mode (dynamic IP, peer with IPv6 neighbors)")
func main() {
@ -240,9 +148,44 @@ func main() {
if err := hjson.Unmarshal(config, &dat); err != nil {
panic(err)
}
// For now we will do a little bit to help the user adjust their
// configuration to match the new configuration format
changes := map[string]string{
"Multicast": "",
"LinkLocal": "MulticastInterfaces",
"BoxPub": "EncryptionPublicKey",
"BoxPriv": "EncryptionPrivateKey",
"SigPub": "SigningPublicKey",
"SigPriv": "SigningPrivateKey",
"AllowedBoxPubs": "AllowedEncryptionPublicKeys",
}
for from, to := range changes {
if _, ok := dat[from]; ok {
if to == "" {
if !*normaliseconf {
log.Println("Warning: Deprecated config option", from, "- please remove")
}
} else {
if !*normaliseconf {
log.Println("Warning: Deprecated config option", from, "- please rename to", to)
}
if _, ok := dat[to]; !ok {
dat[to] = dat[from]
}
}
}
}
if err = mapstructure.Decode(dat, &cfg); err != nil {
panic(err)
}
if *normaliseconf {
bs, err := hjson.Marshal(cfg)
if err != nil {
panic(err)
}
fmt.Println(string(bs))
return
}
case *genconf:
fmt.Println(doGenconf())
default:
@ -277,25 +220,6 @@ func main() {
subnet = append(subnet, 0, 0, 0, 0, 0, 0, 0, 0)
logger.Printf("Your IPv6 address is %s", net.IP(address).String())
logger.Printf("Your IPv6 subnet is %s/64", net.IP(subnet).String())
if cfg.Multicast {
addr, err := net.ResolveUDPAddr("udp", multicastAddr)
if err != nil {
panic(err)
}
listenString := fmt.Sprintf("[::]:%v", addr.Port)
conn, err := net.ListenPacket("udp6", listenString)
if err != nil {
panic(err)
}
//defer conn.Close() // Let it close on its own when the application exits
n.sock = ipv6.NewPacketConn(conn)
if err = n.sock.SetControlMessage(ipv6.FlagDst, true); err != nil {
// Windows can't set this flag, so we need to handle it in other ways
//panic(err)
}
go n.listen()
go n.announce()
}
// Catch interrupt to exit gracefully
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)

View File

@ -155,7 +155,7 @@ func main() {
fmt.Println("TAP mode:", tap_mode)
}
}
case "addPeer", "removePeer", "addAllowedBoxPub", "removeAllowedBoxPub":
case "addPeer", "removePeer", "addAllowedEncryptionPublicKey", "removeAllowedEncryptionPublicKey":
if _, ok := res["added"]; ok {
for _, v := range res["added"].([]interface{}) {
fmt.Println("Added:", fmt.Sprint(v))
@ -176,7 +176,7 @@ func main() {
fmt.Println("Not removed:", fmt.Sprint(v))
}
}
case "getAllowedBoxPubs":
case "getAllowedEncryptionPublicKeys":
if _, ok := res["allowed_box_pubs"]; !ok {
fmt.Println("All connections are allowed")
} else if res["allowed_box_pubs"] == nil {