355 lines
9.8 KiB
Go
Raw Normal View History

2017-12-28 22:16:20 -06:00
package yggdrasil
2018-06-12 17:50:08 -05:00
import (
"encoding/hex"
"io/ioutil"
"net"
"time"
2018-06-12 17:50:08 -05:00
"github.com/gologme/log"
"github.com/yggdrasil-network/yggdrasil-go/src/address"
2018-12-07 19:56:04 -06:00
"github.com/yggdrasil-network/yggdrasil-go/src/config"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
2018-06-12 17:50:08 -05:00
)
2017-12-28 22:16:20 -06:00
var buildName string
var buildVersion string
2018-05-27 22:13:37 +01:00
// The Core object represents the Yggdrasil node. You should create a Core
// object for each Yggdrasil node you plan to run.
2017-12-28 22:16:20 -06:00
type Core struct {
2018-01-04 22:37:51 +00:00
// This is the main data structure that holds everything else for a node
// We're going to keep our own copy of the provided config - that way we can
// guarantee that it will be covered by the mutex
config config.NodeState // Config
2018-12-29 19:14:26 +00:00
boxPub crypto.BoxPubKey
boxPriv crypto.BoxPrivKey
sigPub crypto.SigPubKey
sigPriv crypto.SigPrivKey
2018-01-04 22:37:51 +00:00
switchTable switchTable
peers peers
sessions sessions
router router
dht dht
2018-01-21 00:17:15 +00:00
admin admin
2018-01-04 22:37:51 +00:00
searches searches
link link
log *log.Logger
2017-12-28 22:16:20 -06:00
}
2018-12-29 19:14:26 +00:00
func (c *Core) init() error {
2018-01-04 22:37:51 +00:00
// TODO separate init and start functions
// Init sets up structs
// Start launches goroutines that depend on structs being set up
// This is pretty much required to completely avoid race conditions
2018-05-27 22:13:37 +01:00
if c.log == nil {
c.log = log.New(ioutil.Discard, "", 0)
}
2018-12-29 19:14:26 +00:00
current, _ := c.config.Get()
boxPubHex, err := hex.DecodeString(current.EncryptionPublicKey)
2018-12-29 19:14:26 +00:00
if err != nil {
return err
}
boxPrivHex, err := hex.DecodeString(current.EncryptionPrivateKey)
2018-12-29 19:14:26 +00:00
if err != nil {
return err
}
sigPubHex, err := hex.DecodeString(current.SigningPublicKey)
2018-12-29 19:14:26 +00:00
if err != nil {
return err
}
sigPrivHex, err := hex.DecodeString(current.SigningPrivateKey)
2018-12-29 19:14:26 +00:00
if err != nil {
return err
}
copy(c.boxPub[:], boxPubHex)
copy(c.boxPriv[:], boxPrivHex)
copy(c.sigPub[:], sigPubHex)
copy(c.sigPriv[:], sigPrivHex)
c.admin.init(c)
2018-01-04 22:37:51 +00:00
c.searches.init(c)
c.dht.init(c)
c.sessions.init(c)
//c.multicast.init(c)
2018-01-04 22:37:51 +00:00
c.peers.init(c)
c.router.init(c)
2018-12-29 19:14:26 +00:00
c.switchTable.init(c) // TODO move before peers? before router?
return nil
2017-12-28 22:16:20 -06:00
}
// If any static peers were provided in the configuration above then we should
// configure them. The loop ensures that disconnected peers will eventually
// be reconnected with.
func (c *Core) addPeerLoop() {
for {
// the peers from the config - these could change!
current, _ := c.config.Get()
// Add peers from the Peers section
for _, peer := range current.Peers {
c.AddPeer(peer, "")
time.Sleep(time.Second)
}
// Add peers from the InterfacePeers section
for intf, intfpeers := range current.InterfacePeers {
for _, peer := range intfpeers {
c.AddPeer(peer, intf)
time.Sleep(time.Second)
}
}
// Sit for a while
time.Sleep(time.Minute)
}
}
// UpdateConfig updates the configuration in Core with the provided
// config.NodeConfig and then signals the various module goroutines to
// reconfigure themselves if needed.
func (c *Core) UpdateConfig(config *config.NodeConfig) {
c.log.Infoln("Reloading configuration...")
c.config.Replace(*config)
errors := 0
2018-12-30 12:04:42 +00:00
components := []chan chan error{
c.admin.reconfigure,
2019-01-14 14:25:52 +00:00
c.searches.reconfigure,
c.dht.reconfigure,
c.sessions.reconfigure,
c.peers.reconfigure,
c.router.reconfigure,
c.router.cryptokey.reconfigure,
2019-01-14 14:25:52 +00:00
c.switchTable.reconfigure,
c.link.reconfigure,
2018-12-30 12:04:42 +00:00
}
for _, component := range components {
response := make(chan error)
component <- response
if err := <-response; err != nil {
c.log.Errorln(err)
errors++
2018-12-30 12:04:42 +00:00
}
}
if errors > 0 {
c.log.Warnln(errors, "modules reported errors during configuration reload")
} else {
c.log.Infoln("Configuration reloaded successfully")
}
}
// BuildName gets the current build name. This is usually injected if built
// from git, or returns "unknown" otherwise.
func BuildName() string {
if buildName == "" {
return "unknown"
}
return buildName
}
// BuildVersion gets the current build version. This is usually injected if
// built from git, or returns "unknown" otherwise.
func BuildVersion() string {
if buildVersion == "" {
return "unknown"
}
return buildVersion
}
// SetRouterAdapter instructs Yggdrasil to use the given adapter when starting
// the router. The adapter must implement the standard
// adapter.adapterImplementation interface and should extend the adapter.Adapter
// struct.
func (c *Core) SetRouterAdapter(adapter interface{}) {
// We do this because adapterImplementation is not a valid type for the
// gomobile bindings so we just ask for a generic interface and try to cast it
// to adapterImplementation instead
if a, ok := adapter.(adapterImplementation); ok {
c.router.adapter = a
}
}
// Start starts up Yggdrasil using the provided config.NodeConfig, and outputs
// debug logging through the provided log.Logger. The started stack will include
// TCP and UDP sockets, a multicast discovery socket, an admin socket, router,
// switch and DHT node. A config.NodeState is returned which contains both the
// current and previous configurations (from reconfigures).
2019-03-28 19:09:19 +00:00
func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) (*config.NodeState, error) {
2018-05-27 22:13:37 +01:00
c.log = log
c.config = config.NodeState{
Current: *nc,
Previous: *nc,
}
if name := BuildName(); name != "unknown" {
c.log.Infoln("Build name:", name)
}
if version := BuildVersion(); version != "unknown" {
c.log.Infoln("Build version:", version)
}
c.log.Infoln("Starting up...")
2018-05-27 22:13:37 +01:00
2018-12-29 19:14:26 +00:00
c.init()
2018-05-27 22:13:37 +01:00
if err := c.link.init(c); err != nil {
c.log.Errorln("Failed to start link interfaces")
2019-03-28 19:09:19 +00:00
return nil, err
}
c.config.Mutex.RLock()
if c.config.Current.SwitchOptions.MaxTotalQueueSize >= SwitchQueueTotalMinSize {
c.switchTable.queueTotalMaxSize = c.config.Current.SwitchOptions.MaxTotalQueueSize
}
c.config.Mutex.RUnlock()
if err := c.switchTable.start(); err != nil {
c.log.Errorln("Failed to start switch")
2019-03-28 19:09:19 +00:00
return nil, err
}
2018-05-27 22:13:37 +01:00
if err := c.router.start(); err != nil {
c.log.Errorln("Failed to start router")
2019-03-28 19:09:19 +00:00
return nil, err
2018-05-27 22:13:37 +01:00
}
if err := c.admin.start(); err != nil {
c.log.Errorln("Failed to start admin socket")
2019-03-28 19:09:19 +00:00
return nil, err
2018-05-27 22:13:37 +01:00
}
if c.router.adapter != nil {
if err := c.router.adapter.Start(c.router.addr, c.router.subnet); err != nil {
c.log.Errorln("Failed to start TUN/TAP")
return nil, err
}
2018-05-27 22:35:30 +01:00
}
go c.addPeerLoop()
c.log.Infoln("Startup complete")
2019-03-28 19:09:19 +00:00
return &c.config, nil
2018-05-27 22:13:37 +01:00
}
// Stop shuts down the Yggdrasil node.
2018-05-27 22:13:37 +01:00
func (c *Core) Stop() {
c.log.Infoln("Stopping...")
if c.router.adapter != nil {
c.router.adapter.Close()
}
2018-07-07 20:04:11 +01:00
c.admin.close()
2018-05-27 22:13:37 +01:00
}
// ListenTCP starts a new TCP listener. The input URI should match that of the
// "Listen" configuration item, e.g.
// tcp://a.b.c.d:e
func (c *Core) ListenTCP(uri string) (*TcpListener, error) {
return c.link.tcp.listen(uri)
}
// NewEncryptionKeys 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) {
return crypto.NewBoxKeys()
2018-05-27 22:13:37 +01:00
}
// NewSigningKeys generates a new signing keypair. The signing keys are used to
// derive the structure of the spanning tree.
func (c *Core) NewSigningKeys() (*crypto.SigPubKey, *crypto.SigPrivKey) {
return crypto.NewSigKeys()
2018-05-27 22:13:37 +01:00
}
// NodeID gets the node ID.
func (c *Core) NodeID() *crypto.NodeID {
2019-03-29 18:24:57 +00:00
return crypto.GetNodeID(&c.boxPub)
2017-12-28 22:16:20 -06:00
}
// TreeID gets the tree ID.
func (c *Core) TreeID() *crypto.TreeID {
2019-03-29 18:24:57 +00:00
return crypto.GetTreeID(&c.sigPub)
2017-12-28 22:16:20 -06:00
}
// Address gets the IPv6 address of the Yggdrasil node. This is always a /128
// address.
func (c *Core) Address() *net.IP {
address := net.IP(address.AddrForNodeID(c.NodeID())[:])
2018-05-27 22:13:37 +01:00
return &address
}
// Subnet gets the routed IPv6 subnet of the Yggdrasil node. This is always a
// /64 subnet.
func (c *Core) Subnet() *net.IPNet {
subnet := address.SubnetForNodeID(c.NodeID())[:]
2018-05-27 22:13:37 +01:00
subnet = append(subnet, 0, 0, 0, 0, 0, 0, 0, 0)
2018-06-02 21:21:05 +01:00
return &net.IPNet{IP: subnet, Mask: net.CIDRMask(64, 128)}
2018-05-27 22:13:37 +01:00
}
// RouterAddresses returns the raw address and subnet types as used by the
2019-03-28 19:09:19 +00:00
// router
func (c *Core) RouterAddresses() (address.Address, address.Subnet) {
2019-03-28 19:09:19 +00:00
return c.router.addr, c.router.subnet
}
// NodeInfo gets the currently configured nodeinfo.
func (c *Core) NodeInfo() nodeinfoPayload {
2019-01-14 19:05:16 +00:00
return c.router.nodeinfo.getNodeInfo()
}
// SetNodeInfo the lcal nodeinfo. Note that nodeinfo can be any value or struct,
// it will be serialised into JSON automatically.
func (c *Core) SetNodeInfo(nodeinfo interface{}, nodeinfoprivacy bool) {
2019-01-14 19:05:16 +00:00
c.router.nodeinfo.setNodeInfo(nodeinfo, nodeinfoprivacy)
}
// SetLogger sets the output logger of the Yggdrasil node after startup. This
// may be useful if you want to redirect the output later.
2018-05-27 22:13:37 +01:00
func (c *Core) SetLogger(log *log.Logger) {
c.log = log
}
// AddPeer adds a peer. This should be specified in the peer URI format, e.g.:
// tcp://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 {
if err := c.CallPeer(addr, sintf); err != nil {
return err
}
c.config.Mutex.Lock()
if sintf == "" {
c.config.Current.Peers = append(c.config.Current.Peers, addr)
} else {
c.config.Current.InterfacePeers[sintf] = append(c.config.Current.InterfacePeers[sintf], addr)
}
c.config.Mutex.Unlock()
return nil
2018-05-27 22:13:37 +01:00
}
// CallPeer calls a peer once. This should be specified in the peer URI format,
// e.g.:
// tcp://a.b.c.d:e
// socks://a.b.c.d:e/f.g.h.i:j
// This does not add the peer to the peer list, so if the connection drops, the
// peer will not be called again automatically.
func (c *Core) CallPeer(addr string, sintf string) error {
return c.link.call(addr, sintf)
}
// AddAllowedEncryptionPublicKey adds an allowed public key. This allow peerings
// to be restricted only to keys that you have selected.
2018-05-27 22:13:37 +01:00
func (c *Core) AddAllowedEncryptionPublicKey(boxStr string) error {
return c.admin.addAllowedEncryptionPublicKey(boxStr)
}