From 088d28a93b5437b259a981a5dde81accf2d8a21c Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sun, 21 Oct 2018 18:04:02 +0100 Subject: [PATCH 01/30] Fix debug builds with friendly names --- src/yggdrasil/debug.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/yggdrasil/debug.go b/src/yggdrasil/debug.go index 892529b..74d4ae0 100644 --- a/src/yggdrasil/debug.go +++ b/src/yggdrasil/debug.go @@ -50,7 +50,7 @@ func StartProfiler(log *log.Logger) error { func (c *Core) Init() { bpub, bpriv := newBoxKeys() spub, spriv := newSigKeys() - c.init(bpub, bpriv, spub, spriv) + c.init(bpub, bpriv, spub, spriv, "(simulator)") c.switchTable.start() c.router.start() } @@ -84,7 +84,7 @@ func (c *Core) DEBUG_getPeers() *peers { func (ps *peers) DEBUG_newPeer(box boxPubKey, sig sigPubKey, link boxSharedKey) *peer { //in <-chan []byte, //out chan<- []byte) *peer { - return ps.newPeer(&box, &sig, &link) //, in, out) + return ps.newPeer(&box, &sig, &link, "(simulator)", "(simulator)") //, in, out) } /* @@ -358,7 +358,7 @@ func (c *Core) DEBUG_init(bpub []byte, copy(boxPriv[:], bpriv) copy(sigPub[:], spub) copy(sigPriv[:], spriv) - c.init(&boxPub, &boxPriv, &sigPub, &sigPriv) + c.init(&boxPub, &boxPriv, &sigPub, &sigPriv, "(simulator)") if err := c.router.start(); err != nil { panic(err) From 4f435705e31dfd2c32e993b10d46dcfd4be88477 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sun, 21 Oct 2018 18:06:54 +0100 Subject: [PATCH 02/30] Fix getSelf in yggdrasilctl --- yggdrasilctl.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/yggdrasilctl.go b/yggdrasilctl.go index 2b5b79a..fd2d9b8 100644 --- a/yggdrasilctl.go +++ b/yggdrasilctl.go @@ -181,6 +181,13 @@ func main() { } case "getself": for k, v := range res["self"].(map[string]interface{}) { + if friendlyname, ok := v.(map[string]interface{})["friendly_name"].(string); ok { + if friendlyname == "" { + fmt.Println("Friendly name: (none)") + } else { + fmt.Println("Friendly name:", friendlyname) + } + } fmt.Println("IPv6 address:", k) if subnet, ok := v.(map[string]interface{})["subnet"].(string); ok { fmt.Println("IPv6 subnet:", subnet) From a1b72c16d8448e66f470df67ae916b47cb98394b Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sun, 21 Oct 2018 22:58:27 +0100 Subject: [PATCH 03/30] Some attempt at exchanging session metadata over the wire (broken) --- src/yggdrasil/admin.go | 6 +- src/yggdrasil/config/config.go | 8 ++- src/yggdrasil/core.go | 55 +++++++------- src/yggdrasil/metadata.go | 7 ++ src/yggdrasil/peer.go | 46 ++++++------ src/yggdrasil/router.go | 17 ++++- src/yggdrasil/session.go | 126 +++++++++++++++++++++++++-------- src/yggdrasil/tcp.go | 2 +- src/yggdrasil/wire.go | 44 ++++++++++++ 9 files changed, 228 insertions(+), 83 deletions(-) create mode 100644 src/yggdrasil/metadata.go diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 630db17..aa73d3b 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -470,7 +470,9 @@ func (a *admin) getData_getSelf() *admin_nodeInfo { {"ip", a.core.GetAddress().String()}, {"subnet", a.core.GetSubnet().String()}, {"coords", fmt.Sprint(coords)}, - {"friendly_name", a.core.friendlyName}, + {"name", a.core.metadata.name}, + {"location", a.core.metadata.location}, + {"contact", a.core.metadata.contact}, } return &self } @@ -494,7 +496,6 @@ func (a *admin) getData_getPeers() []admin_nodeInfo { {"bytes_sent", atomic.LoadUint64(&p.bytesSent)}, {"bytes_recvd", atomic.LoadUint64(&p.bytesRecvd)}, {"endpoint", p.endpoint}, - {"friendly_name", p.friendlyName}, } peerInfos = append(peerInfos, info) } @@ -520,7 +521,6 @@ func (a *admin) getData_getSwitchPeers() []admin_nodeInfo { {"bytes_sent", atomic.LoadUint64(&peer.bytesSent)}, {"bytes_recvd", atomic.LoadUint64(&peer.bytesRecvd)}, {"endpoint", peer.endpoint}, - {"friendly_name", peer.friendlyName}, } peerInfos = append(peerInfos, info) } diff --git a/src/yggdrasil/config/config.go b/src/yggdrasil/config/config.go index 530c18c..04c95c2 100644 --- a/src/yggdrasil/config/config.go +++ b/src/yggdrasil/config/config.go @@ -2,7 +2,7 @@ package config // NodeConfig defines all configuration values needed to run a signle yggdrasil node type NodeConfig struct { - FriendlyName string `comment:"Friendly name for this node. It is visible to direct peers."` + Metadata Metadata `comment:"Optional node metadata. Entirely optional but visible to all\npeers and nodes with open sessions."` Listen string `comment:"Listen address for peer connections. Default is to listen for all\nTCP connections over IPv4 and IPv6 with a random port."` AdminListen string `comment:"Listen address for admin connections Default is to listen for local\nconnections either on TCP/9001 or a UNIX socket depending on your\nplatform. Use this value for yggdrasilctl -endpoint=X."` Peers []string `comment:"List of connection strings for static peers in URI format, i.e.\ntcp://a.b.c.d:e or socks://a.b.c.d:e/f.g.h.i:j."` @@ -35,3 +35,9 @@ type SessionFirewall struct { WhitelistEncryptionPublicKeys []string `comment:"List of public keys from which network traffic is always accepted,\nregardless of AllowFromDirect or AllowFromRemote."` BlacklistEncryptionPublicKeys []string `comment:"List of public keys from which network traffic is always rejected,\nregardless of the whitelist, AllowFromDirect or AllowFromRemote."` } + +type Metadata struct { + Name string + Location string + Contact string +} diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 8f61bf6..9be08ab 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -16,31 +16,31 @@ import ( // object for each Yggdrasil node you plan to run. type Core struct { // This is the main data structure that holds everything else for a node - boxPub boxPubKey - boxPriv boxPrivKey - sigPub sigPubKey - sigPriv sigPrivKey - friendlyName string - switchTable switchTable - peers peers - sigs sigManager - sessions sessions - router router - dht dht - tun tunDevice - admin admin - searches searches - multicast multicast - tcp tcpInterface - log *log.Logger - ifceExpr []*regexp.Regexp // the zone of link-local IPv6 peers must match this + boxPub boxPubKey + boxPriv boxPrivKey + sigPub sigPubKey + sigPriv sigPrivKey + metadata metadata + switchTable switchTable + peers peers + sigs sigManager + sessions sessions + router router + dht dht + tun tunDevice + admin admin + searches searches + multicast multicast + tcp tcpInterface + log *log.Logger + ifceExpr []*regexp.Regexp // the zone of link-local IPv6 peers must match this } func (c *Core) init(bpub *boxPubKey, bpriv *boxPrivKey, spub *sigPubKey, spriv *sigPrivKey, - friendlyname string) { + metadata metadata) { // TODO separate init and start functions // Init sets up structs // Start launches goroutines that depend on structs being set up @@ -51,7 +51,7 @@ func (c *Core) init(bpub *boxPubKey, } c.boxPub, c.boxPriv = *bpub, *bpriv c.sigPub, c.sigPriv = *spub, *spriv - c.friendlyName = friendlyname + c.metadata = metadata c.admin.core = c c.sigs.init() c.searches.init(c) @@ -65,11 +65,8 @@ func (c *Core) init(bpub *boxPubKey, } // Gets the friendly name of this node, as specified in the NodeConfig. -func (c *Core) GetFriendlyName() string { - if c.friendlyName == "" { - return "(none)" - } - return c.friendlyName +func (c *Core) GetMeta() metadata { + return c.metadata } // Starts up Yggdrasil using the provided NodeConfig, and outputs debug logging @@ -105,7 +102,13 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { copy(sigPub[:], sigPubHex) copy(sigPriv[:], sigPrivHex) - c.init(&boxPub, &boxPriv, &sigPub, &sigPriv, nc.FriendlyName) + meta := metadata{ + name: nc.Metadata.Name, + location: nc.Metadata.Location, + contact: nc.Metadata.Contact, + } + + c.init(&boxPub, &boxPriv, &sigPub, &sigPriv, meta) c.admin.init(c, nc.AdminListen) if err := c.tcp.init(c, nc.Listen, nc.ReadTimeout); err != nil { diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go new file mode 100644 index 0000000..c524308 --- /dev/null +++ b/src/yggdrasil/metadata.go @@ -0,0 +1,7 @@ +package yggdrasil + +type metadata struct { + name string + location string + contact string +} diff --git a/src/yggdrasil/peer.go b/src/yggdrasil/peer.go index 4f79237..da807c9 100644 --- a/src/yggdrasil/peer.go +++ b/src/yggdrasil/peer.go @@ -79,34 +79,34 @@ type peer struct { bytesSent uint64 // To track bandwidth usage for getPeers bytesRecvd uint64 // To track bandwidth usage for getPeers // BUG: sync/atomic, 32 bit platforms need the above to be the first element - core *Core - port switchPort - box boxPubKey - sig sigPubKey - shared boxSharedKey - linkShared boxSharedKey - endpoint string - friendlyName string - firstSeen time.Time // To track uptime for getPeers - linkOut (chan []byte) // used for protocol traffic (to bypass queues) - doSend (chan struct{}) // tell the linkLoop to send a switchMsg - dinfo *dhtInfo // used to keep the DHT working - out func([]byte) // Set up by whatever created the peers struct, used to send packets to other nodes - close func() // Called when a peer is removed, to close the underlying connection, or via admin api + core *Core + port switchPort + box boxPubKey + sig sigPubKey + shared boxSharedKey + linkShared boxSharedKey + endpoint string + metadata metadata + firstSeen time.Time // To track uptime for getPeers + linkOut (chan []byte) // used for protocol traffic (to bypass queues) + doSend (chan struct{}) // tell the linkLoop to send a switchMsg + dinfo *dhtInfo // used to keep the DHT working + out func([]byte) // Set up by whatever created the peers struct, used to send packets to other nodes + close func() // Called when a peer is removed, to close the underlying connection, or via admin api } // Creates a new peer with the specified box, sig, and linkShared keys, using the lowest unocupied port number. -func (ps *peers) newPeer(box *boxPubKey, sig *sigPubKey, linkShared *boxSharedKey, endpoint string, friendlyname string) *peer { +func (ps *peers) newPeer(box *boxPubKey, sig *sigPubKey, linkShared *boxSharedKey, endpoint string, metadata metadata) *peer { now := time.Now() p := peer{box: *box, - sig: *sig, - shared: *getSharedKey(&ps.core.boxPriv, box), - linkShared: *linkShared, - endpoint: endpoint, - friendlyName: friendlyname, - firstSeen: now, - doSend: make(chan struct{}, 1), - core: ps.core} + sig: *sig, + shared: *getSharedKey(&ps.core.boxPriv, box), + linkShared: *linkShared, + endpoint: endpoint, + metadata: metadata, + firstSeen: now, + doSend: make(chan struct{}, 1), + core: ps.core} ps.mutex.Lock() defer ps.mutex.Unlock() oldPorts := ps.getPorts() diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index dcc6a5c..bcec258 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -47,7 +47,7 @@ func (r *router) init(core *Core) { r.core = core r.addr = *address_addrForNodeID(&r.core.dht.nodeID) in := make(chan []byte, 32) // TODO something better than this... - p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)", r.core.GetFriendlyName()) + p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)", r.core.metadata) p.out = func(packet []byte) { // This is to make very sure it never blocks select { @@ -324,6 +324,10 @@ func (r *router) handleProto(packet []byte) { r.handlePing(bs, &p.FromKey) case wire_SessionPong: r.handlePong(bs, &p.FromKey) + case wire_SessionMetaRequest: + fallthrough + case wire_SessionMetaResponse: + r.handleMeta(bs, &p.FromKey) case wire_DHTLookupRequest: r.handleDHTReq(bs, &p.FromKey) case wire_DHTLookupResponse: @@ -368,6 +372,17 @@ func (r *router) handleDHTRes(bs []byte, fromKey *boxPubKey) { r.core.dht.handleRes(&res) } +// Decodes meta request +func (r *router) handleMeta(bs []byte, fromKey *boxPubKey) { + req := sessionMeta{} + if !req.decode(bs) { + return + } + req.SendPermPub = *fromKey + r.core.log.Printf("handleMeta: %+v\n", req) + r.core.sessions.handleMeta(&req) +} + // Passed a function to call. // This will send the function to r.admin and block until it finishes. // It's used by the admin socket to ask the router mainLoop goroutine about information in the session or dht structs, which cannot be read safely from outside that goroutine. diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index 0bc27a1..39ea4cb 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -13,34 +13,37 @@ import ( // All the information we know about an active session. // This includes coords, permanent and ephemeral keys, handles and nonces, various sorts of timing information for timeout and maintenance, and some metadata for the admin API. type sessionInfo struct { - core *Core - theirAddr address - theirSubnet subnet - theirPermPub boxPubKey - theirSesPub boxPubKey - mySesPub boxPubKey - mySesPriv boxPrivKey - sharedSesKey boxSharedKey // derived from session keys - theirHandle handle - myHandle handle - theirNonce boxNonce - myNonce boxNonce - theirMTU uint16 - myMTU uint16 - wasMTUFixed bool // Was the MTU fixed by a receive error? - time time.Time // Time we last received a packet - coords []byte // coords of destination - packet []byte // a buffered packet, sent immediately on ping/pong - init bool // Reset if coords change - send chan []byte - recv chan *wire_trafficPacket - nonceMask uint64 - tstamp int64 // tstamp from their last session ping, replay attack mitigation - mtuTime time.Time // time myMTU was last changed - pingTime time.Time // time the first ping was sent since the last received packet - pingSend time.Time // time the last ping was sent - bytesSent uint64 // Bytes of real traffic sent in this session - bytesRecvd uint64 // Bytes of real traffic received in this session + core *Core + theirAddr address + theirSubnet subnet + theirPermPub boxPubKey + theirSesPub boxPubKey + mySesPub boxPubKey + mySesPriv boxPrivKey + sharedSesKey boxSharedKey // derived from session keys + theirHandle handle + myHandle handle + theirNonce boxNonce + myNonce boxNonce + metaReqTime time.Time + metaResTime time.Time + theirMetadata metadata + theirMTU uint16 + myMTU uint16 + wasMTUFixed bool // Was the MTU fixed by a receive error? + time time.Time // Time we last received a packet + coords []byte // coords of destination + packet []byte // a buffered packet, sent immediately on ping/pong + init bool // Reset if coords change + send chan []byte + recv chan *wire_trafficPacket + nonceMask uint64 + tstamp int64 // tstamp from their last session ping, replay attack mitigation + mtuTime time.Time // time myMTU was last changed + pingTime time.Time // time the first ping was sent since the last received packet + pingSend time.Time // time the last ping was sent + bytesSent uint64 // Bytes of real traffic sent in this session + bytesRecvd uint64 // Bytes of real traffic received in this session } // Represents a session ping/pong packet, andincludes information like public keys, a session handle, coords, a timestamp to prevent replays, and the tun/tap MTU. @@ -54,6 +57,13 @@ type sessionPing struct { MTU uint16 } +// Represents a session metadata packet. +type sessionMeta struct { + SendPermPub boxPubKey // Sender's permanent key + IsResponse bool + Metadata metadata +} + // Updates session info in response to a ping, after checking that the ping is OK. // Returns true if the session was updated, or false otherwise. func (s *sessionInfo) update(p *sessionPing) bool { @@ -431,6 +441,66 @@ func (ss *sessions) handlePing(ping *sessionPing) { bs, sinfo.packet = sinfo.packet, nil ss.core.router.sendPacket(bs) } + if time.Since(sinfo.metaResTime).Minutes() > 15 { + if time.Since(sinfo.metaReqTime).Minutes() > 1 { + ss.sendMeta(sinfo, false) + } + } +} + +func (ss *sessions) sendMeta(sinfo *sessionInfo, isResponse bool) { + meta := sessionMeta{ + IsResponse: isResponse, + Metadata: metadata{ + name: "some.name.com", //[]byte(ss.core.friendlyName)[0:len(ss.core.friendlyName):32], + location: "Some Place", + contact: "someone@somewhere.com", + }, + } + bs := meta.encode() + shared := ss.getSharedKey(&ss.core.boxPriv, &sinfo.theirPermPub) + payload, nonce := boxSeal(shared, bs, nil) + p := wire_protoTrafficPacket{ + Coords: sinfo.coords, + ToKey: sinfo.theirPermPub, + FromKey: ss.core.boxPub, + Nonce: *nonce, + Payload: payload, + } + packet := p.encode() + ss.core.router.out(packet) + if isResponse { + ss.core.log.Println("Sent meta response to", sinfo.theirAddr) + } else { + ss.core.log.Println("Sent meta request to", sinfo.theirAddr) + sinfo.metaReqTime = time.Now() + } +} + +// Handles a meta request/response. +func (ss *sessions) handleMeta(meta *sessionMeta) { + // Get the corresponding session (or create a new session) + sinfo, isIn := ss.getByTheirPerm(&meta.SendPermPub) + // Check the session firewall + if !isIn && ss.sessionFirewallEnabled { + if !ss.isSessionAllowed(&meta.SendPermPub, false) { + return + } + } + if !isIn || sinfo.timedout() { + return + } + if meta.IsResponse { + ss.core.log.Println("Received meta response", string(meta.Metadata.name), "from", sinfo.theirAddr) + sinfo.theirMetadata = meta.Metadata + sinfo.metaResTime = time.Now() + ss.core.log.Println("- name:", meta.Metadata.name) + ss.core.log.Println("- contact:", meta.Metadata.contact) + ss.core.log.Println("- location:", meta.Metadata.location) + } else { + ss.core.log.Println("Received meta request", string(meta.Metadata.name), "from", sinfo.theirAddr) + ss.sendMeta(sinfo, true) + } } // Used to subtract one nonce from another, staying in the range +- 64. diff --git a/src/yggdrasil/tcp.go b/src/yggdrasil/tcp.go index 58d9422..dc1e2b1 100644 --- a/src/yggdrasil/tcp.go +++ b/src/yggdrasil/tcp.go @@ -287,7 +287,7 @@ func (iface *tcpInterface) handler(sock net.Conn, incoming bool) { }() // Note that multiple connections to the same node are allowed // E.g. over different interfaces - p := iface.core.peers.newPeer(&info.box, &info.sig, getSharedKey(myLinkPriv, &meta.link), sock.RemoteAddr().String(), "(none)") + p := iface.core.peers.newPeer(&info.box, &info.sig, getSharedKey(myLinkPriv, &meta.link), sock.RemoteAddr().String(), metadata{}) p.linkOut = make(chan []byte, 1) in := func(bs []byte) { p.handlePacket(bs) diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index d05624e..fd898a6 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -16,6 +16,8 @@ const ( wire_SessionPong // inside protocol traffic header wire_DHTLookupRequest // inside protocol traffic header wire_DHTLookupResponse // inside protocol traffic header + wire_SessionMetaRequest // inside protocol traffic header + wire_SessionMetaResponse // inside protocol traffic header ) // Calls wire_put_uint64 on a nil slice. @@ -353,6 +355,48 @@ func (p *sessionPing) decode(bs []byte) bool { //////////////////////////////////////////////////////////////////////////////// +// Encodes a sessionPing into its wire format. +func (p *sessionMeta) encode() []byte { + var pTypeVal uint64 + if p.IsResponse { + pTypeVal = wire_SessionMetaResponse + } else { + pTypeVal = wire_SessionMetaRequest + } + bs := wire_encode_uint64(pTypeVal) + if p.IsResponse { + bs = append(bs, p.Metadata.name...) + bs = append(bs, p.Metadata.location...) + bs = append(bs, p.Metadata.contact...) + } + return bs +} + +// Decodes an encoded sessionPing into the struct, returning true if successful. +func (p *sessionMeta) decode(bs []byte) bool { + var pType uint64 + switch { + case !wire_chop_uint64(&pType, &bs): + return false + case pType != wire_SessionMetaRequest && pType != wire_SessionMetaResponse: + return false + } + p.IsResponse = pType == wire_SessionMetaResponse + if p.IsResponse { + switch { + case !wire_chop_slice([]byte(p.Metadata.name), &bs): + return false + case !wire_chop_slice([]byte(p.Metadata.location), &bs): + return false + case !wire_chop_slice([]byte(p.Metadata.contact), &bs): + return false + } + } + return true +} + +//////////////////////////////////////////////////////////////////////////////// + // Encodes a dhtReq into its wire format. func (r *dhtReq) encode() []byte { coords := wire_encode_coords(r.Coords) From 97464feba9394d7403abdceb63e024ac8b26e675 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Wed, 12 Dec 2018 19:51:28 +0000 Subject: [PATCH 04/30] Working metadata exchange --- src/config/config.go | 9 +-------- src/yggdrasil/admin.go | 3 --- src/yggdrasil/core.go | 16 ++++------------ src/yggdrasil/metadata.go | 7 ------- src/yggdrasil/router.go | 3 +-- src/yggdrasil/session.go | 25 +++++++++++-------------- src/yggdrasil/wire.go | 17 +++++------------ 7 files changed, 22 insertions(+), 58 deletions(-) delete mode 100644 src/yggdrasil/metadata.go diff --git a/src/config/config.go b/src/config/config.go index 18950a4..66de668 100644 --- a/src/config/config.go +++ b/src/config/config.go @@ -2,7 +2,6 @@ package config // NodeConfig defines all configuration values needed to run a signle yggdrasil node type NodeConfig struct { - Metadata Metadata `comment:"Optional node metadata. Entirely optional but visible to all\npeers and nodes with open sessions."` Listen string `comment:"Listen address for peer connections. Default is to listen for all\nTCP connections over IPv4 and IPv6 with a random port."` AdminListen string `comment:"Listen address for admin connections. Default is to listen for local\nconnections either on TCP/9001 or a UNIX socket depending on your\nplatform. Use this value for yggdrasilctl -endpoint=X. To disable\nthe admin socket, use the value \"none\" instead."` Peers []string `comment:"List of connection strings for static peers in URI format, e.g.\ntcp://a.b.c.d:e or socks://a.b.c.d:e/f.g.h.i:j."` @@ -20,6 +19,7 @@ type NodeConfig struct { SessionFirewall SessionFirewall `comment:"The session firewall controls who can send/receive network traffic\nto/from. This is useful if you want to protect this node without\nresorting to using a real firewall. This does not affect traffic\nbeing routed via this node to somewhere else. Rules are prioritised as\nfollows: blacklist, whitelist, always allow outgoing, direct, remote."` TunnelRouting TunnelRouting `comment:"Allow tunneling non-Yggdrasil traffic over Yggdrasil. This effectively\nallows you to use Yggdrasil to route to, or to bridge other networks,\nsimilar to a VPN tunnel. Tunnelling works between any two nodes and\ndoes not require them to be directly peered."` SwitchOptions SwitchOptions `comment:"Advanced options for tuning the switch. Normally you will not need\nto edit these options."` + Metadata interface{} `comment:"Optional node metadata. Entirely optional but visible to all\npeers and nodes with open sessions."` //Net NetConfig `comment:"Extended options for connecting to peers over other networks."` } @@ -52,10 +52,3 @@ type TunnelRouting struct { type SwitchOptions struct { MaxTotalQueueSize uint64 `comment:"Maximum size of all switch queues combined (in bytes)."` } - -// Optional metadata - format subject to change -type Metadata struct { - Name string - Location string - Contact string -} diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 332fa1c..266d5a8 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -574,9 +574,6 @@ func (a *admin) getData_getSelf() *admin_nodeInfo { {"ip", a.core.GetAddress().String()}, {"subnet", a.core.GetSubnet().String()}, {"coords", fmt.Sprint(coords)}, - {"name", a.core.metadata.name}, - {"location", a.core.metadata.location}, - {"contact", a.core.metadata.contact}, } if name := GetBuildName(); name != "unknown" { self = append(self, admin_pair{"build_name", name}) diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 06a3cb3..5a9267c 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -23,7 +23,6 @@ type Core struct { boxPriv boxPrivKey sigPub sigPubKey sigPriv sigPrivKey - metadata metadata switchTable switchTable peers peers sessions sessions @@ -41,8 +40,7 @@ type Core struct { func (c *Core) init(bpub *boxPubKey, bpriv *boxPrivKey, spub *sigPubKey, - spriv *sigPrivKey, - metadata metadata) { + spriv *sigPrivKey) { // TODO separate init and start functions // Init sets up structs // Start launches goroutines that depend on structs being set up @@ -53,7 +51,6 @@ func (c *Core) init(bpub *boxPubKey, } c.boxPub, c.boxPriv = *bpub, *bpriv c.sigPub, c.sigPriv = *spub, *spriv - c.metadata = metadata c.admin.core = c c.searches.init(c) c.dht.init(c) @@ -85,7 +82,7 @@ func GetBuildVersion() string { // Gets the friendly name of this node, as specified in the NodeConfig. func (c *Core) GetMeta() metadata { - return c.metadata + return c.sessions.myMetadata } // Starts up Yggdrasil using the provided NodeConfig, and outputs debug logging @@ -129,13 +126,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { copy(sigPub[:], sigPubHex) copy(sigPriv[:], sigPrivHex) - meta := metadata{ - name: nc.Metadata.Name, - location: nc.Metadata.Location, - contact: nc.Metadata.Contact, - } - - c.init(&boxPub, &boxPriv, &sigPub, &sigPriv, meta) + c.init(&boxPub, &boxPriv, &sigPub, &sigPriv) c.admin.init(c, nc.AdminListen) if err := c.tcp.init(c, nc.Listen, nc.ReadTimeout); err != nil { @@ -152,6 +143,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { return err } + c.sessions.setMetadata(metadata("HIYA, THIS IS METADATA")) c.sessions.setSessionFirewallState(nc.SessionFirewall.Enable) c.sessions.setSessionFirewallDefaults( nc.SessionFirewall.AllowFromDirect, diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go deleted file mode 100644 index c524308..0000000 --- a/src/yggdrasil/metadata.go +++ /dev/null @@ -1,7 +0,0 @@ -package yggdrasil - -type metadata struct { - name string - location string - contact string -} diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index 2df359d..a40563b 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -58,7 +58,7 @@ func (r *router) init(core *Core) { r.addr = *address_addrForNodeID(&r.core.dht.nodeID) r.subnet = *address_subnetForNodeID(&r.core.dht.nodeID) in := make(chan []byte, 32) // TODO something better than this... - p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)", r.core.metadata) + p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)", r.core.sessions.myMetadata) p.out = func(packet []byte) { // This is to make very sure it never blocks select { @@ -483,7 +483,6 @@ func (r *router) handleMeta(bs []byte, fromKey *boxPubKey) { return } req.SendPermPub = *fromKey - r.core.log.Printf("handleMeta: %+v\n", req) r.core.sessions.handleMeta(&req) } diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index e088726..690f603 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -64,6 +64,8 @@ type sessionMeta struct { Metadata metadata } +type metadata []byte + // Updates session info in response to a ping, after checking that the ping is OK. // Returns true if the session was updated, or false otherwise. func (s *sessionInfo) update(p *sessionPing) bool { @@ -125,6 +127,8 @@ type sessions struct { sessionFirewallAlwaysAllowsOutbound bool sessionFirewallWhitelist []string sessionFirewallBlacklist []string + // Metadata for this node + myMetadata metadata } // Initializes the session struct. @@ -139,6 +143,11 @@ func (ss *sessions) init(core *Core) { ss.lastCleanup = time.Now() } +// Enable or disable the session firewall +func (ss *sessions) setMetadata(meta metadata) { + ss.myMetadata = meta +} + // Enable or disable the session firewall func (ss *sessions) setSessionFirewallState(enabled bool) { ss.sessionFirewallEnabled = enabled @@ -486,11 +495,7 @@ func (ss *sessions) handlePing(ping *sessionPing) { func (ss *sessions) sendMeta(sinfo *sessionInfo, isResponse bool) { meta := sessionMeta{ IsResponse: isResponse, - Metadata: metadata{ - name: "some.name.com", //[]byte(ss.core.friendlyName)[0:len(ss.core.friendlyName):32], - location: "Some Place", - contact: "someone@somewhere.com", - }, + Metadata: ss.myMetadata, } bs := meta.encode() shared := ss.getSharedKey(&ss.core.boxPriv, &sinfo.theirPermPub) @@ -504,10 +509,7 @@ func (ss *sessions) sendMeta(sinfo *sessionInfo, isResponse bool) { } packet := p.encode() ss.core.router.out(packet) - if isResponse { - ss.core.log.Println("Sent meta response to", sinfo.theirAddr) - } else { - ss.core.log.Println("Sent meta request to", sinfo.theirAddr) + if !isResponse { sinfo.metaReqTime = time.Now() } } @@ -526,14 +528,9 @@ func (ss *sessions) handleMeta(meta *sessionMeta) { return } if meta.IsResponse { - ss.core.log.Println("Received meta response", string(meta.Metadata.name), "from", sinfo.theirAddr) sinfo.theirMetadata = meta.Metadata sinfo.metaResTime = time.Now() - ss.core.log.Println("- name:", meta.Metadata.name) - ss.core.log.Println("- contact:", meta.Metadata.contact) - ss.core.log.Println("- location:", meta.Metadata.location) } else { - ss.core.log.Println("Received meta request", string(meta.Metadata.name), "from", sinfo.theirAddr) ss.sendMeta(sinfo, true) } } diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index fd898a6..7f394d7 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -364,10 +364,8 @@ func (p *sessionMeta) encode() []byte { pTypeVal = wire_SessionMetaRequest } bs := wire_encode_uint64(pTypeVal) - if p.IsResponse { - bs = append(bs, p.Metadata.name...) - bs = append(bs, p.Metadata.location...) - bs = append(bs, p.Metadata.contact...) + if pTypeVal == wire_SessionMetaResponse { + bs = append(bs, p.Metadata...) } return bs } @@ -381,14 +379,9 @@ func (p *sessionMeta) decode(bs []byte) bool { case pType != wire_SessionMetaRequest && pType != wire_SessionMetaResponse: return false } - p.IsResponse = pType == wire_SessionMetaResponse - if p.IsResponse { - switch { - case !wire_chop_slice([]byte(p.Metadata.name), &bs): - return false - case !wire_chop_slice([]byte(p.Metadata.location), &bs): - return false - case !wire_chop_slice([]byte(p.Metadata.contact), &bs): + if p.IsResponse = pType == wire_SessionMetaResponse; p.IsResponse { + p.Metadata = make(metadata, len(bs)) + if !wire_chop_slice(p.Metadata[:], &bs) { return false } } From 042a3400fe08050ae0e30b8e453ae2f59bb5c50d Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Wed, 12 Dec 2018 22:40:49 +0000 Subject: [PATCH 05/30] Wrap the metadata with a mutex to guarantee thread safety across core/router/sessions --- src/yggdrasil/core.go | 15 ++++++++++----- src/yggdrasil/router.go | 2 ++ src/yggdrasil/session.go | 30 +++++++++++++++++++++++------- src/yggdrasil/wire.go | 7 +++++-- 4 files changed, 40 insertions(+), 14 deletions(-) diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 5a9267c..72a11d7 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -80,11 +80,6 @@ func GetBuildVersion() string { return buildVersion } -// Gets the friendly name of this node, as specified in the NodeConfig. -func (c *Core) GetMeta() metadata { - return c.sessions.myMetadata -} - // Starts up Yggdrasil using the provided 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 @@ -245,6 +240,16 @@ func (c *Core) GetSubnet() *net.IPNet { return &net.IPNet{IP: subnet, Mask: net.CIDRMask(64, 128)} } +// Gets the node metadata. +func (c *Core) GetMetadata() metadata { + return c.sessions.getMetadata() +} + +// Sets the node metadata. +func (c *Core) SetMetadata(meta metadata) { + c.sessions.setMetadata(meta) +} + // Sets the output logger of the Yggdrasil node after startup. This may be // useful if you want to redirect the output later. func (c *Core) SetLogger(log *log.Logger) { diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index a40563b..8ac59d8 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -58,7 +58,9 @@ func (r *router) init(core *Core) { r.addr = *address_addrForNodeID(&r.core.dht.nodeID) r.subnet = *address_subnetForNodeID(&r.core.dht.nodeID) in := make(chan []byte, 32) // TODO something better than this... + r.core.sessions.myMetadataMutex.RLock() p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)", r.core.sessions.myMetadata) + r.core.sessions.myMetadataMutex.RUnlock() p.out = func(packet []byte) { // This is to make very sure it never blocks select { diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index 690f603..a7bed8a 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -7,6 +7,7 @@ package yggdrasil import ( "bytes" "encoding/hex" + "sync" "time" ) @@ -128,7 +129,8 @@ type sessions struct { sessionFirewallWhitelist []string sessionFirewallBlacklist []string // Metadata for this node - myMetadata metadata + myMetadata metadata + myMetadataMutex sync.RWMutex } // Initializes the session struct. @@ -143,8 +145,17 @@ func (ss *sessions) init(core *Core) { ss.lastCleanup = time.Now() } -// Enable or disable the session firewall +// Get the metadata +func (ss *sessions) getMetadata() metadata { + ss.myMetadataMutex.RLock() + defer ss.myMetadataMutex.RUnlock() + return ss.myMetadata +} + +// Set the metadata func (ss *sessions) setMetadata(meta metadata) { + ss.myMetadataMutex.Lock() + defer ss.myMetadataMutex.Unlock() ss.myMetadata = meta } @@ -485,18 +496,23 @@ func (ss *sessions) handlePing(ping *sessionPing) { bs, sinfo.packet = sinfo.packet, nil ss.core.router.sendPacket(bs) } - if time.Since(sinfo.metaResTime).Minutes() > 15 { - if time.Since(sinfo.metaReqTime).Minutes() > 1 { - ss.sendMeta(sinfo, false) - } - } + // This requests metadata from the remote side fairly quickly after + // establishing the session, and if other time constraints apply (no more + // often than 15 minutes since receiving the last metadata) + //if time.Since(sinfo.metaResTime).Minutes() > 15 { + // if time.Since(sinfo.metaReqTime).Minutes() > 1 { + // ss.sendMeta(sinfo, false) + // } + //} } func (ss *sessions) sendMeta(sinfo *sessionInfo, isResponse bool) { + ss.myMetadataMutex.RLock() meta := sessionMeta{ IsResponse: isResponse, Metadata: ss.myMetadata, } + ss.myMetadataMutex.RUnlock() bs := meta.encode() shared := ss.getSharedKey(&ss.core.boxPriv, &sinfo.theirPermPub) payload, nonce := boxSeal(shared, bs, nil) diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index 7f394d7..2d87a37 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -355,7 +355,7 @@ func (p *sessionPing) decode(bs []byte) bool { //////////////////////////////////////////////////////////////////////////////// -// Encodes a sessionPing into its wire format. +// Encodes a sessionMeta into its wire format. func (p *sessionMeta) encode() []byte { var pTypeVal uint64 if p.IsResponse { @@ -370,7 +370,7 @@ func (p *sessionMeta) encode() []byte { return bs } -// Decodes an encoded sessionPing into the struct, returning true if successful. +// Decodes an encoded sessionMeta into the struct, returning true if successful. func (p *sessionMeta) decode(bs []byte) bool { var pType uint64 switch { @@ -380,6 +380,9 @@ func (p *sessionMeta) decode(bs []byte) bool { return false } if p.IsResponse = pType == wire_SessionMetaResponse; p.IsResponse { + if len(bs) == 0 { + return false + } p.Metadata = make(metadata, len(bs)) if !wire_chop_slice(p.Metadata[:], &bs) { return false From 74de8c9416f716a2d90f836b5878d2ac5aba0c41 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Wed, 12 Dec 2018 22:48:04 +0000 Subject: [PATCH 06/30] Consistent function naming for metadata --- src/yggdrasil/router.go | 6 +++--- src/yggdrasil/session.go | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index 8ac59d8..b0655eb 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -433,7 +433,7 @@ func (r *router) handleProto(packet []byte) { case wire_SessionMetaRequest: fallthrough case wire_SessionMetaResponse: - r.handleMeta(bs, &p.FromKey) + r.handleMetadata(bs, &p.FromKey) case wire_DHTLookupRequest: r.handleDHTReq(bs, &p.FromKey) case wire_DHTLookupResponse: @@ -479,13 +479,13 @@ func (r *router) handleDHTRes(bs []byte, fromKey *boxPubKey) { } // Decodes meta request -func (r *router) handleMeta(bs []byte, fromKey *boxPubKey) { +func (r *router) handleMetadata(bs []byte, fromKey *boxPubKey) { req := sessionMeta{} if !req.decode(bs) { return } req.SendPermPub = *fromKey - r.core.sessions.handleMeta(&req) + r.core.sessions.handleMetadata(&req) } // Passed a function to call. diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index a7bed8a..6a49d58 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -501,12 +501,12 @@ func (ss *sessions) handlePing(ping *sessionPing) { // often than 15 minutes since receiving the last metadata) //if time.Since(sinfo.metaResTime).Minutes() > 15 { // if time.Since(sinfo.metaReqTime).Minutes() > 1 { - // ss.sendMeta(sinfo, false) + // ss.sendMetadata(sinfo, false) // } //} } -func (ss *sessions) sendMeta(sinfo *sessionInfo, isResponse bool) { +func (ss *sessions) sendMetadata(sinfo *sessionInfo, isResponse bool) { ss.myMetadataMutex.RLock() meta := sessionMeta{ IsResponse: isResponse, @@ -531,7 +531,7 @@ func (ss *sessions) sendMeta(sinfo *sessionInfo, isResponse bool) { } // Handles a meta request/response. -func (ss *sessions) handleMeta(meta *sessionMeta) { +func (ss *sessions) handleMetadata(meta *sessionMeta) { // Get the corresponding session (or create a new session) sinfo, isIn := ss.getByTheirPerm(&meta.SendPermPub) // Check the session firewall @@ -547,7 +547,7 @@ func (ss *sessions) handleMeta(meta *sessionMeta) { sinfo.theirMetadata = meta.Metadata sinfo.metaResTime = time.Now() } else { - ss.sendMeta(sinfo, true) + ss.sendMetadata(sinfo, true) } } From 2056e75ad58d400dbff995722e3f840e23fe24d5 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Wed, 12 Dec 2018 22:51:00 +0000 Subject: [PATCH 07/30] Remove friendlyname fields from yggdrasilctl --- cmd/yggdrasilctl/main.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/cmd/yggdrasilctl/main.go b/cmd/yggdrasilctl/main.go index f09e5d8..b37c256 100644 --- a/cmd/yggdrasilctl/main.go +++ b/cmd/yggdrasilctl/main.go @@ -256,13 +256,6 @@ func main() { if buildversion, ok := v.(map[string]interface{})["build_version"].(string); ok && buildversion != "unknown" { fmt.Println("Build version:", buildversion) } - if friendlyname, ok := v.(map[string]interface{})["friendly_name"].(string); ok { - if friendlyname == "" { - fmt.Println("Friendly name: (none)") - } else { - fmt.Println("Friendly name:", friendlyname) - } - } fmt.Println("IPv6 address:", k) if subnet, ok := v.(map[string]interface{})["subnet"].(string); ok { fmt.Println("IPv6 subnet:", subnet) From 64060a447c5301e3ac0602f6730a9b46909fdc08 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Wed, 12 Dec 2018 22:58:16 +0000 Subject: [PATCH 08/30] Remove metadata-peer association until we have some sensible way to cache it --- src/yggdrasil/peer.go | 4 +--- src/yggdrasil/router.go | 4 +--- src/yggdrasil/session.go | 1 + src/yggdrasil/tcp.go | 2 +- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/yggdrasil/peer.go b/src/yggdrasil/peer.go index 4a81cb8..abdfa0c 100644 --- a/src/yggdrasil/peer.go +++ b/src/yggdrasil/peer.go @@ -86,7 +86,6 @@ type peer struct { shared boxSharedKey linkShared boxSharedKey endpoint string - metadata metadata firstSeen time.Time // To track uptime for getPeers linkOut (chan []byte) // used for protocol traffic (to bypass queues) doSend (chan struct{}) // tell the linkLoop to send a switchMsg @@ -96,14 +95,13 @@ type peer struct { } // Creates a new peer with the specified box, sig, and linkShared keys, using the lowest unocupied port number. -func (ps *peers) newPeer(box *boxPubKey, sig *sigPubKey, linkShared *boxSharedKey, endpoint string, metadata metadata) *peer { +func (ps *peers) newPeer(box *boxPubKey, sig *sigPubKey, linkShared *boxSharedKey, endpoint string) *peer { now := time.Now() p := peer{box: *box, sig: *sig, shared: *getSharedKey(&ps.core.boxPriv, box), linkShared: *linkShared, endpoint: endpoint, - metadata: metadata, firstSeen: now, doSend: make(chan struct{}, 1), core: ps.core} diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index b0655eb..4914a6b 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -58,9 +58,7 @@ func (r *router) init(core *Core) { r.addr = *address_addrForNodeID(&r.core.dht.nodeID) r.subnet = *address_subnetForNodeID(&r.core.dht.nodeID) in := make(chan []byte, 32) // TODO something better than this... - r.core.sessions.myMetadataMutex.RLock() - p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)", r.core.sessions.myMetadata) - r.core.sessions.myMetadataMutex.RUnlock() + p := r.core.peers.newPeer(&r.core.boxPub, &r.core.sigPub, &boxSharedKey{}, "(self)") p.out = func(packet []byte) { // This is to make very sure it never blocks select { diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index 6a49d58..31fe375 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -546,6 +546,7 @@ func (ss *sessions) handleMetadata(meta *sessionMeta) { if meta.IsResponse { sinfo.theirMetadata = meta.Metadata sinfo.metaResTime = time.Now() + } else { ss.sendMetadata(sinfo, true) } diff --git a/src/yggdrasil/tcp.go b/src/yggdrasil/tcp.go index dc1e2b1..5ca6630 100644 --- a/src/yggdrasil/tcp.go +++ b/src/yggdrasil/tcp.go @@ -287,7 +287,7 @@ func (iface *tcpInterface) handler(sock net.Conn, incoming bool) { }() // Note that multiple connections to the same node are allowed // E.g. over different interfaces - p := iface.core.peers.newPeer(&info.box, &info.sig, getSharedKey(myLinkPriv, &meta.link), sock.RemoteAddr().String(), metadata{}) + p := iface.core.peers.newPeer(&info.box, &info.sig, getSharedKey(myLinkPriv, &meta.link), sock.RemoteAddr().String()) p.linkOut = make(chan []byte, 1) in := func(bs []byte) { p.handlePacket(bs) From a9907a78788b8698d80d053f390d415f3c58047d Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Wed, 12 Dec 2018 22:59:55 +0000 Subject: [PATCH 09/30] Fix debug builds after 64060a4 --- src/yggdrasil/debug.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/yggdrasil/debug.go b/src/yggdrasil/debug.go index 9a56e28..e463518 100644 --- a/src/yggdrasil/debug.go +++ b/src/yggdrasil/debug.go @@ -50,7 +50,7 @@ func StartProfiler(log *log.Logger) error { func (c *Core) Init() { bpub, bpriv := newBoxKeys() spub, spriv := newSigKeys() - c.init(bpub, bpriv, spub, spriv, metadata{}) + c.init(bpub, bpriv, spub, spriv) c.switchTable.start() c.router.start() } @@ -84,7 +84,7 @@ func (c *Core) DEBUG_getPeers() *peers { func (ps *peers) DEBUG_newPeer(box boxPubKey, sig sigPubKey, link boxSharedKey) *peer { //in <-chan []byte, //out chan<- []byte) *peer { - return ps.newPeer(&box, &sig, &link, "(simulator)", metadata{}) //, in, out) + return ps.newPeer(&box, &sig, &link, "(simulator)") //, in, out) } /* @@ -356,7 +356,7 @@ func (c *Core) DEBUG_init(bpub []byte, copy(boxPriv[:], bpriv) copy(sigPub[:], spub) copy(sigPriv[:], spriv) - c.init(&boxPub, &boxPriv, &sigPub, &sigPriv, metadata{}) + c.init(&boxPub, &boxPriv, &sigPub, &sigPriv) if err := c.router.start(); err != nil { panic(err) From e1c79837527ace57a8e5e9aaef01a80e2b2ef21c Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 14:25:26 +0000 Subject: [PATCH 10/30] Update debian package to fix systemd disabling (not good for remote systems) and add group yggdrasil for admin socket/conf --- contrib/deb/generate.sh | 24 +++++++++++++++++------- contrib/systemd/yggdrasil.service | 3 ++- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/contrib/deb/generate.sh b/contrib/deb/generate.sh index 618f00f..0eb2188 100644 --- a/contrib/deb/generate.sh +++ b/contrib/deb/generate.sh @@ -71,29 +71,39 @@ etc/systemd/system/*.service etc/systemd/system EOF cat > /tmp/$PKGNAME/debian/postinst << EOF #!/bin/sh + +if ! getent group yggdrasil 2>&1 > /dev/null; then + addgroup --system --quiet yggdrasil +fi + if [ -f /etc/yggdrasil.conf ]; then mkdir -p /var/backups echo "Backing up configuration file to /var/backups/yggdrasil.conf.`date +%Y%m%d`" cp /etc/yggdrasil.conf /var/backups/yggdrasil.conf.`date +%Y%m%d` - echo "Normalising /etc/yggdrasil.conf" + echo "Normalising and updating /etc/yggdrasil.conf" /usr/bin/yggdrasil -useconffile /var/backups/yggdrasil.conf.`date +%Y%m%d` -normaliseconf > /etc/yggdrasil.conf -fi -if command -v systemctl >/dev/null; then - systemctl daemon-reload >/dev/null || true - if [ -f /etc/systemd/system/multi-user.target.wants/yggdrasil.service ]; then - echo "Starting Yggdrasil" + chgrp yggdrasil /etc/yggdrasil.conf + + if command -v systemctl >/dev/null; then + systemctl daemon-reload >/dev/null || true + systemctl enable yggdrasil || true systemctl start yggdrasil || true fi +else + echo "Generating initial configuration file /etc/yggdrasil.conf" + echo "Please familiarise yourself with this file before starting Yggdrasil" + /usr/bin/yggdrasil -genconf > /etc/yggdrasil.conf + chgrp yggdrasil /etc/yggdrasil.conf fi EOF cat > /tmp/$PKGNAME/debian/prerm << EOF #!/bin/sh if command -v systemctl >/dev/null; then if systemctl is-active --quiet yggdrasil; then - echo "Stopping Yggdrasil" systemctl stop yggdrasil || true fi + systemctl disable yggdrasil || true fi EOF diff --git a/contrib/systemd/yggdrasil.service b/contrib/systemd/yggdrasil.service index 9ae4a07..1b6f1f0 100644 --- a/contrib/systemd/yggdrasil.service +++ b/contrib/systemd/yggdrasil.service @@ -4,6 +4,7 @@ Wants=network.target After=network.target [Service] +Group=yggdrasil ProtectHome=true ProtectSystem=true SyslogIdentifier=yggdrasil @@ -12,7 +13,7 @@ ExecStartPre=/bin/sh -ec "if ! test -s /etc/yggdrasil.conf; \ yggdrasil -genconf > /etc/yggdrasil.conf; \ echo 'WARNING: A new /etc/yggdrasil.conf file has been generated.'; \ fi" -ExecStart=/bin/sh -c "exec yggdrasil -useconf < /etc/yggdrasil.conf" +ExecStart=/usr/bin/yggdrasil -useconffile /etc/yggdrasil.conf Restart=always [Install] From 10157483f9bd36a5b02ee20569c908f6d8d75914 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 17:35:02 +0000 Subject: [PATCH 11/30] Move tunDevice into router --- src/yggdrasil/admin.go | 18 +++++++++--------- src/yggdrasil/core.go | 10 ++++------ src/yggdrasil/router.go | 14 ++++++++++---- src/yggdrasil/session.go | 2 +- 4 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 266d5a8..e80ca39 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -160,9 +160,9 @@ func (a *admin) init(c *Core, listenaddr string) { }() return admin_info{ - a.core.tun.iface.Name(): admin_info{ - "tap_mode": a.core.tun.iface.IsTAP(), - "mtu": a.core.tun.mtu, + a.core.router.tun.iface.Name(): admin_info{ + "tap_mode": a.core.router.tun.iface.IsTAP(), + "mtu": a.core.router.tun.mtu, }, }, nil }) @@ -185,8 +185,8 @@ func (a *admin) init(c *Core, listenaddr string) { return admin_info{}, errors.New("Failed to configure adapter") } else { return admin_info{ - a.core.tun.iface.Name(): admin_info{ - "tap_mode": a.core.tun.iface.IsTAP(), + a.core.router.tun.iface.Name(): admin_info{ + "tap_mode": a.core.router.tun.iface.IsTAP(), "mtu": ifmtu, }, }, nil @@ -539,12 +539,12 @@ func (a *admin) removePeer(p string) error { // startTunWithMTU creates the tun/tap device, sets its address, and sets the MTU to the provided value. func (a *admin) startTunWithMTU(ifname string, iftapmode bool, ifmtu int) error { // Close the TUN first if open - _ = a.core.tun.close() + _ = a.core.router.tun.close() // Then reconfigure and start it addr := a.core.router.addr straddr := fmt.Sprintf("%s/%v", net.IP(addr[:]).String(), 8*len(address_prefix)-1) if ifname != "none" { - err := a.core.tun.setup(ifname, iftapmode, straddr, ifmtu) + err := a.core.router.tun.setup(ifname, iftapmode, straddr, ifmtu) if err != nil { return err } @@ -559,9 +559,9 @@ func (a *admin) startTunWithMTU(ifname string, iftapmode bool, ifmtu int) error a.core.sessions.sendPingPong(sinfo, false) } // Aaaaand... go! - go a.core.tun.read() + go a.core.router.tun.read() } - go a.core.tun.write() + go a.core.router.tun.write() return nil } diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 5ab91a7..13609ce 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -28,7 +28,6 @@ type Core struct { sessions sessions router router dht dht - tun tunDevice admin admin searches searches multicast multicast @@ -59,7 +58,6 @@ func (c *Core) init(bpub *boxPubKey, c.peers.init(c) c.router.init(c) c.switchTable.init(c, c.sigPub) // TODO move before peers? before router? - c.tun.init(c) } // Get the current build name. This is usually injected if built from git, @@ -188,7 +186,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { } ip := net.IP(c.router.addr[:]).String() - if err := c.tun.start(nc.IfName, nc.IfTAPMode, fmt.Sprintf("%s/%d", ip, 8*len(address_prefix)-1), nc.IfMTU); err != nil { + if err := c.router.tun.start(nc.IfName, nc.IfTAPMode, fmt.Sprintf("%s/%d", ip, 8*len(address_prefix)-1), nc.IfMTU); err != nil { c.log.Println("Failed to start TUN/TAP") return err } @@ -200,7 +198,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { // Stops the Yggdrasil node. func (c *Core) Stop() { c.log.Println("Stopping...") - c.tun.close() + c.router.tun.close() c.admin.close() } @@ -293,10 +291,10 @@ func (c *Core) GetTUNDefaultIfTAPMode() bool { // Gets the current TUN/TAP interface name. func (c *Core) GetTUNIfName() string { - return c.tun.iface.Name() + return c.router.tun.iface.Name() } // Gets the current TUN/TAP interface MTU. func (c *Core) GetTUNIfMTU() int { - return c.tun.mtu + return c.router.tun.mtu } diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index b482476..eab18b1 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -30,6 +30,10 @@ import ( "golang.org/x/net/ipv6" ) +type adapter struct { + tunDevice +} + // The router struct has channels to/from the tun/tap device and a self peer (0), which is how messages are passed between this node and the peers/switch layer. // The router's mainLoop goroutine is responsible for managing all information related to the dht, searches, and crypto sessions. type router struct { @@ -39,6 +43,7 @@ type router struct { in <-chan []byte // packets we received from the network, link to peer's "out" out func([]byte) // packets we're sending to the network, link to peer's "in" toRecv chan router_recvPacket // packets to handle via recvPacket() + tun tunDevice // TUN/TAP adapter recv chan<- []byte // place where the tun pulls received packets from send <-chan []byte // place where the tun puts outgoing packets reset chan struct{} // signal that coords changed (re-init sessions/dht) @@ -75,11 +80,12 @@ func (r *router) init(core *Core) { send := make(chan []byte, 32) r.recv = recv r.send = send - r.core.tun.recv = recv - r.core.tun.send = send + r.tun.recv = recv + r.tun.send = send r.reset = make(chan struct{}, 1) r.admin = make(chan func(), 32) r.cryptokey.init(r.core) + r.tun.init(r.core) // go r.mainLoop() } @@ -279,7 +285,7 @@ func (r *router) sendPacket(bs []byte) { } // Create the ICMPv6 response from it - icmpv6Buf, err := r.core.tun.icmpv6.create_icmpv6_tun( + icmpv6Buf, err := r.tun.icmpv6.create_icmpv6_tun( bs[8:24], bs[24:40], ipv6.ICMPTypeDestinationUnreachable, 1, ptb) if err == nil { @@ -304,7 +310,7 @@ func (r *router) sendPacket(bs []byte) { } // Create the ICMPv6 response from it - icmpv6Buf, err := r.core.tun.icmpv6.create_icmpv6_tun( + icmpv6Buf, err := r.tun.icmpv6.create_icmpv6_tun( bs[8:24], bs[24:40], ipv6.ICMPTypePacketTooBig, 0, ptb) if err == nil { diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index 92ae262..4f2bedf 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -273,7 +273,7 @@ func (ss *sessions) createSession(theirPermKey *boxPubKey) *sessionInfo { sinfo.mySesPriv = *priv sinfo.myNonce = *newBoxNonce() sinfo.theirMTU = 1280 - sinfo.myMTU = uint16(ss.core.tun.mtu) + sinfo.myMTU = uint16(ss.core.router.tun.mtu) now := time.Now() sinfo.time = now sinfo.mtuTime = now From ccf6ce07a444f8acdc3cba86db16ff89c59d1c43 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 17:49:42 +0000 Subject: [PATCH 12/30] Fix Peers and InterfacePeers when not in correct format --- cmd/yggdrasil/main.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cmd/yggdrasil/main.go b/cmd/yggdrasil/main.go index 5b75690..ec8c712 100644 --- a/cmd/yggdrasil/main.go +++ b/cmd/yggdrasil/main.go @@ -12,6 +12,7 @@ import ( "os" "os/signal" "regexp" + "strings" "syscall" "time" @@ -188,6 +189,25 @@ func main() { } } } + // Check to see if the peers are in a parsable format, if not then default + // them to the TCP scheme + for index, peer := range dat["Peers"].([]interface{}) { + uri := peer.(string) + if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { + continue + } + (dat["Peers"].([]interface{}))[index] = "tcp://" + uri + } + // Now do the same with the interface peers + for intf, peers := range dat["InterfacePeers"].(map[string]interface{}) { + for index, peer := range peers.([]interface{}) { + uri := peer.(string) + if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { + continue + } + ((dat["InterfacePeers"].(map[string]interface{}))[intf]).([]interface{})[index] = "tcp://" + uri + } + } // Overlay our newly mapped configuration onto the autoconf node config that // we generated above. if err = mapstructure.Decode(dat, &cfg); err != nil { From 3ca5f10733fe86241fb185dcac0291bd5d30df94 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 17:52:54 +0000 Subject: [PATCH 13/30] Don't try to correct peers with no schemes in addPeer --- src/yggdrasil/admin.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index e80ca39..577b6ef 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -515,13 +515,7 @@ func (a *admin) addPeer(addr string, sintf string) error { return errors.New("invalid peer: " + addr) } } else { - // no url scheme provided - addr = strings.ToLower(addr) - if strings.HasPrefix(addr, "tcp:") { - addr = addr[4:] - } - a.core.tcp.connect(addr, "") - return nil + return errors.New("invalid peer: " + addr) } return nil } From 1a7df477b011aafeb5425c16ee84087128c9fa54 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 17:55:07 +0000 Subject: [PATCH 14/30] Also correct tcp: into tcp:// --- cmd/yggdrasil/main.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cmd/yggdrasil/main.go b/cmd/yggdrasil/main.go index ec8c712..ee5375b 100644 --- a/cmd/yggdrasil/main.go +++ b/cmd/yggdrasil/main.go @@ -196,6 +196,9 @@ func main() { if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { continue } + if strings.HasPrefix(uri, "tcp:") { + uri = uri[4:] + } (dat["Peers"].([]interface{}))[index] = "tcp://" + uri } // Now do the same with the interface peers @@ -205,6 +208,9 @@ func main() { if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { continue } + if strings.HasPrefix(uri, "tcp:") { + uri = uri[4:] + } ((dat["InterfacePeers"].(map[string]interface{}))[intf]).([]interface{})[index] = "tcp://" + uri } } From 9eaa2566c1d032d5769574f5825352568374c79f Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 18:08:13 +0000 Subject: [PATCH 15/30] Parameterise tun.init --- src/yggdrasil/router.go | 5 +---- src/yggdrasil/tun.go | 4 +++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index eab18b1..3b6d204 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -80,13 +80,10 @@ func (r *router) init(core *Core) { send := make(chan []byte, 32) r.recv = recv r.send = send - r.tun.recv = recv - r.tun.send = send r.reset = make(chan struct{}, 1) r.admin = make(chan func(), 32) r.cryptokey.init(r.core) - r.tun.init(r.core) - // go r.mainLoop() + r.tun.init(r.core, send, recv) } // Starts the mainLoop goroutine. diff --git a/src/yggdrasil/tun.go b/src/yggdrasil/tun.go index e462502..85204da 100644 --- a/src/yggdrasil/tun.go +++ b/src/yggdrasil/tun.go @@ -36,9 +36,11 @@ func getSupportedMTU(mtu int) int { } // Initialises the TUN/TAP adapter. -func (tun *tunDevice) init(core *Core) { +func (tun *tunDevice) init(core *Core, send chan<- []byte, recv <-chan []byte) { tun.core = core tun.icmpv6.init(tun) + tun.send = send + tun.recv = recv } // Starts the setup process for the TUN/TAP adapter, and if successful, starts From 2a38ad07cde19d911ff2ee4a41fbb3c346f8f82f Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 18:08:40 +0000 Subject: [PATCH 16/30] Don't send ICMPv6 back when tun disabled --- src/yggdrasil/router.go | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index 3b6d204..d016d1c 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -270,25 +270,6 @@ func (r *router) sendPacket(bs []byte) { // Drop packets if the session MTU is 0 - this means that one or other // side probably has their TUN adapter disabled if sinfo.getMTU() == 0 { - // Get the size of the oversized payload, up to a max of 900 bytes - window := 900 - if len(bs) < window { - window = len(bs) - } - - // Create the Destination Unreachable response - ptb := &icmp.DstUnreach{ - Data: bs[:window], - } - - // Create the ICMPv6 response from it - icmpv6Buf, err := r.tun.icmpv6.create_icmpv6_tun( - bs[8:24], bs[24:40], - ipv6.ICMPTypeDestinationUnreachable, 1, ptb) - if err == nil { - r.recv <- icmpv6Buf - } - // Don't continue - drop the packet return } From f28360ce4d5d56fe3965bfebe624a0077e53fc6c Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 18:10:39 +0000 Subject: [PATCH 17/30] Fix debug builds (foiled by debug builds every time) --- src/yggdrasil/debug.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/yggdrasil/debug.go b/src/yggdrasil/debug.go index e463518..e5bceee 100644 --- a/src/yggdrasil/debug.go +++ b/src/yggdrasil/debug.go @@ -68,11 +68,11 @@ func (c *Core) DEBUG_getEncryptionPublicKey() boxPubKey { } func (c *Core) DEBUG_getSend() chan<- []byte { - return c.tun.send + return c.router.tun.send } func (c *Core) DEBUG_getRecv() <-chan []byte { - return c.tun.recv + return c.router.tun.recv } // Peer @@ -304,18 +304,18 @@ func (c *Core) DEBUG_startTunWithMTU(ifname string, iftapmode bool, mtu int) { addr := c.DEBUG_getAddr() straddr := fmt.Sprintf("%s/%v", net.IP(addr[:]).String(), 8*len(address_prefix)) if ifname != "none" { - err := c.tun.setup(ifname, iftapmode, straddr, mtu) + err := c.router.tun.setup(ifname, iftapmode, straddr, mtu) if err != nil { panic(err) } - c.log.Println("Setup TUN/TAP:", c.tun.iface.Name(), straddr) - go func() { panic(c.tun.read()) }() + c.log.Println("Setup TUN/TAP:", c.router.tun.iface.Name(), straddr) + go func() { panic(c.router.tun.read()) }() } - go func() { panic(c.tun.write()) }() + go func() { panic(c.router.tun.write()) }() } func (c *Core) DEBUG_stopTun() { - c.tun.close() + c.router.tun.close() } //////////////////////////////////////////////////////////////////////////////// @@ -546,7 +546,7 @@ func DEBUG_simLinkPeers(p, q *peer) { } func (c *Core) DEBUG_simFixMTU() { - c.tun.mtu = 65535 + c.router.tun.mtu = 65535 } //////////////////////////////////////////////////////////////////////////////// From 8045cb4dc3c5e165c848ce0ab4fe7c71bd99d615 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 18:21:08 +0000 Subject: [PATCH 18/30] Define generic adapter type, rename tunDevice to tunAdapter --- src/yggdrasil/icmpv6.go | 4 ++-- src/yggdrasil/router.go | 7 +++++-- src/yggdrasil/tun.go | 16 +++++++--------- src/yggdrasil/tun_bsd.go | 4 ++-- src/yggdrasil/tun_darwin.go | 4 ++-- src/yggdrasil/tun_linux.go | 4 ++-- src/yggdrasil/tun_other.go | 4 ++-- src/yggdrasil/tun_windows.go | 6 +++--- 8 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/yggdrasil/icmpv6.go b/src/yggdrasil/icmpv6.go index 957b192..6e9a265 100644 --- a/src/yggdrasil/icmpv6.go +++ b/src/yggdrasil/icmpv6.go @@ -24,7 +24,7 @@ type macAddress [6]byte const len_ETHER = 14 type icmpv6 struct { - tun *tunDevice + tun *tunAdapter mylladdr net.IP mymac macAddress peermacs map[address]neighbor @@ -57,7 +57,7 @@ func ipv6Header_Marshal(h *ipv6.Header) ([]byte, error) { // Initialises the ICMPv6 module by assigning our link-local IPv6 address and // our MAC address. ICMPv6 messages will always appear to originate from these // addresses. -func (i *icmpv6) init(t *tunDevice) { +func (i *icmpv6) init(t *tunAdapter) { i.tun = t i.peermacs = make(map[address]neighbor) diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index d016d1c..dd9f05d 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -31,7 +31,9 @@ import ( ) type adapter struct { - tunDevice + core *Core + send chan<- []byte + recv <-chan []byte } // The router struct has channels to/from the tun/tap device and a self peer (0), which is how messages are passed between this node and the peers/switch layer. @@ -43,7 +45,8 @@ type router struct { in <-chan []byte // packets we received from the network, link to peer's "out" out func([]byte) // packets we're sending to the network, link to peer's "in" toRecv chan router_recvPacket // packets to handle via recvPacket() - tun tunDevice // TUN/TAP adapter + tun tunAdapter // TUN/TAP adapter + adapters []adapter // Other adapters recv chan<- []byte // place where the tun pulls received packets from send <-chan []byte // place where the tun puts outgoing packets reset chan struct{} // signal that coords changed (re-init sessions/dht) diff --git a/src/yggdrasil/tun.go b/src/yggdrasil/tun.go index 85204da..223092e 100644 --- a/src/yggdrasil/tun.go +++ b/src/yggdrasil/tun.go @@ -17,11 +17,9 @@ const tun_IPv6_HEADER_LENGTH = 40 const tun_ETHER_HEADER_LENGTH = 14 // Represents a running TUN/TAP interface. -type tunDevice struct { - core *Core +type tunAdapter struct { + adapter icmpv6 icmpv6 - send chan<- []byte - recv <-chan []byte mtu int iface *water.Interface } @@ -36,7 +34,7 @@ func getSupportedMTU(mtu int) int { } // Initialises the TUN/TAP adapter. -func (tun *tunDevice) init(core *Core, send chan<- []byte, recv <-chan []byte) { +func (tun *tunAdapter) init(core *Core, send chan<- []byte, recv <-chan []byte) { tun.core = core tun.icmpv6.init(tun) tun.send = send @@ -45,7 +43,7 @@ func (tun *tunDevice) init(core *Core, send chan<- []byte, recv <-chan []byte) { // Starts the setup process for the TUN/TAP adapter, and if successful, starts // the read/write goroutines to handle packets on that interface. -func (tun *tunDevice) start(ifname string, iftapmode bool, addr string, mtu int) error { +func (tun *tunAdapter) start(ifname string, iftapmode bool, addr string, mtu int) error { if ifname == "none" { return nil } @@ -77,7 +75,7 @@ func (tun *tunDevice) start(ifname string, iftapmode bool, addr string, mtu int) // Writes a packet to the TUN/TAP adapter. If the adapter is running in TAP // mode then additional ethernet encapsulation is added for the benefit of the // host operating system. -func (tun *tunDevice) write() error { +func (tun *tunAdapter) write() error { for { data := <-tun.recv if tun.iface == nil { @@ -166,7 +164,7 @@ func (tun *tunDevice) write() error { // is running in TAP mode then the ethernet headers will automatically be // processed and stripped if necessary. If an ICMPv6 packet is found, then // the relevant helper functions in icmpv6.go are called. -func (tun *tunDevice) read() error { +func (tun *tunAdapter) read() error { mtu := tun.mtu if tun.iface.IsTAP() { mtu += tun_ETHER_HEADER_LENGTH @@ -203,7 +201,7 @@ func (tun *tunDevice) read() error { // Closes the TUN/TAP adapter. This is only usually called when the Yggdrasil // process stops. Typically this operation will happen quickly, but on macOS // it can block until a read operation is completed. -func (tun *tunDevice) close() error { +func (tun *tunAdapter) close() error { if tun.iface == nil { return nil } diff --git a/src/yggdrasil/tun_bsd.go b/src/yggdrasil/tun_bsd.go index ca5eaea..620c79d 100644 --- a/src/yggdrasil/tun_bsd.go +++ b/src/yggdrasil/tun_bsd.go @@ -77,7 +77,7 @@ type in6_ifreq_lifetime struct { // a system socket and making syscalls to the kernel. This is not refined though // and often doesn't work (if at all), therefore if a call fails, it resorts // to calling "ifconfig" instead. -func (tun *tunDevice) 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 if ifname[:4] == "auto" { ifname = "/dev/tap0" @@ -103,7 +103,7 @@ func (tun *tunDevice) setup(ifname string, iftapmode bool, addr string, mtu int) return tun.setupAddress(addr) } -func (tun *tunDevice) setupAddress(addr string) error { +func (tun *tunAdapter) setupAddress(addr string) error { var sfd int var err error diff --git a/src/yggdrasil/tun_darwin.go b/src/yggdrasil/tun_darwin.go index e49ab52..943468e 100644 --- a/src/yggdrasil/tun_darwin.go +++ b/src/yggdrasil/tun_darwin.go @@ -14,7 +14,7 @@ import ( ) // Configures the "utun" adapter with the correct IPv6 address and MTU. -func (tun *tunDevice) 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 { tun.core.log.Printf("TAP mode is not supported on this platform, defaulting to TUN") } @@ -62,7 +62,7 @@ type ifreq struct { // Sets the IPv6 address of the utun adapter. On Darwin/macOS this is done using // a system socket and making direct syscalls to the kernel. -func (tun *tunDevice) setupAddress(addr string) error { +func (tun *tunAdapter) setupAddress(addr string) error { var fd int var err error diff --git a/src/yggdrasil/tun_linux.go b/src/yggdrasil/tun_linux.go index aa9e791..7a7c9cb 100644 --- a/src/yggdrasil/tun_linux.go +++ b/src/yggdrasil/tun_linux.go @@ -13,7 +13,7 @@ import ( ) // Configures the TAP adapter with the correct IPv6 address and MTU. -func (tun *tunDevice) 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 if iftapmode { config = water.Config{DeviceType: water.TAP} @@ -48,7 +48,7 @@ func (tun *tunDevice) 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" // to exist on the system, but this will fail if Netlink is not present in the // kernel (it nearly always is). -func (tun *tunDevice) setupAddress(addr string) error { +func (tun *tunAdapter) setupAddress(addr string) error { // Set address var netIF *net.Interface ifces, err := net.Interfaces() diff --git a/src/yggdrasil/tun_other.go b/src/yggdrasil/tun_other.go index 1a3721a..625f9cd 100644 --- a/src/yggdrasil/tun_other.go +++ b/src/yggdrasil/tun_other.go @@ -9,7 +9,7 @@ import water "github.com/yggdrasil-network/water" // Creates the TUN/TAP adapter, if supported by the Water library. Note that // no guarantees are made at this point on an unsupported platform. -func (tun *tunDevice) 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 if iftapmode { config = water.Config{DeviceType: water.TAP} @@ -27,7 +27,7 @@ func (tun *tunDevice) setup(ifname string, iftapmode bool, addr string, mtu int) // We don't know how to set the IPv6 address on an unknown platform, therefore // write about it to stdout and don't try to do anything further. -func (tun *tunDevice) setupAddress(addr string) error { +func (tun *tunAdapter) setupAddress(addr string) error { tun.core.log.Println("Platform not supported, you must set the address of", tun.iface.Name(), "to", addr) return nil } diff --git a/src/yggdrasil/tun_windows.go b/src/yggdrasil/tun_windows.go index d3420df..150a976 100644 --- a/src/yggdrasil/tun_windows.go +++ b/src/yggdrasil/tun_windows.go @@ -13,7 +13,7 @@ import ( // Configures the TAP adapter with the correct IPv6 address and MTU. On Windows // we don't make use of a direct operating system API to do this - we instead // delegate the hard work to "netsh". -func (tun *tunDevice) 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 { tun.core.log.Printf("TUN mode is not supported on this platform, defaulting to TAP") } @@ -65,7 +65,7 @@ func (tun *tunDevice) setup(ifname string, iftapmode bool, addr string, mtu int) } // Sets the MTU of the TAP adapter. -func (tun *tunDevice) setupMTU(mtu int) error { +func (tun *tunAdapter) setupMTU(mtu int) error { // Set MTU cmd := exec.Command("netsh", "interface", "ipv6", "set", "subinterface", fmt.Sprintf("interface=%s", tun.iface.Name()), @@ -82,7 +82,7 @@ func (tun *tunDevice) setupMTU(mtu int) error { } // Sets the IPv6 address of the TAP adapter. -func (tun *tunDevice) setupAddress(addr string) error { +func (tun *tunAdapter) setupAddress(addr string) error { // Set address cmd := exec.Command("netsh", "interface", "ipv6", "add", "address", fmt.Sprintf("interface=%s", tun.iface.Name()), From f9dc300787a3a871144585b813610d6776dd6fc0 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Fri, 14 Dec 2018 18:29:00 +0000 Subject: [PATCH 19/30] Define Adapter base type/interface --- src/yggdrasil/adapter.go | 25 +++++++++++++++++++++++++ src/yggdrasil/router.go | 10 ++-------- src/yggdrasil/tun.go | 6 ++---- 3 files changed, 29 insertions(+), 12 deletions(-) create mode 100644 src/yggdrasil/adapter.go diff --git a/src/yggdrasil/adapter.go b/src/yggdrasil/adapter.go new file mode 100644 index 0000000..4a43209 --- /dev/null +++ b/src/yggdrasil/adapter.go @@ -0,0 +1,25 @@ +package yggdrasil + +// Defines the minimum required functions for an adapter type. +type AdapterInterface interface { + init(core *Core, send chan<- []byte, recv <-chan []byte) + read() error + write() error + close() error +} + +// Defines the minimum required struct members for an adapter type (this is +// now the base type for tunAdapter in tun.go) +type Adapter struct { + AdapterInterface + core *Core + send chan<- []byte + recv <-chan []byte +} + +// Initialises the adapter. +func (adapter *Adapter) init(core *Core, send chan<- []byte, recv <-chan []byte) { + adapter.core = core + adapter.send = send + adapter.recv = recv +} diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index dd9f05d..62480bc 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -30,12 +30,6 @@ import ( "golang.org/x/net/ipv6" ) -type adapter struct { - core *Core - send chan<- []byte - recv <-chan []byte -} - // The router struct has channels to/from the tun/tap device and a self peer (0), which is how messages are passed between this node and the peers/switch layer. // The router's mainLoop goroutine is responsible for managing all information related to the dht, searches, and crypto sessions. type router struct { @@ -45,8 +39,8 @@ type router struct { in <-chan []byte // packets we received from the network, link to peer's "out" out func([]byte) // packets we're sending to the network, link to peer's "in" toRecv chan router_recvPacket // packets to handle via recvPacket() - tun tunAdapter // TUN/TAP adapter - adapters []adapter // Other adapters + tun tunAdapter // TUN/TAP adapter + adapters []Adapter // Other adapters recv chan<- []byte // place where the tun pulls received packets from send <-chan []byte // place where the tun puts outgoing packets reset chan struct{} // signal that coords changed (re-init sessions/dht) diff --git a/src/yggdrasil/tun.go b/src/yggdrasil/tun.go index 223092e..26d32c0 100644 --- a/src/yggdrasil/tun.go +++ b/src/yggdrasil/tun.go @@ -18,7 +18,7 @@ const tun_ETHER_HEADER_LENGTH = 14 // Represents a running TUN/TAP interface. type tunAdapter struct { - adapter + Adapter icmpv6 icmpv6 mtu int iface *water.Interface @@ -35,10 +35,8 @@ func getSupportedMTU(mtu int) int { // Initialises the TUN/TAP adapter. func (tun *tunAdapter) init(core *Core, send chan<- []byte, recv <-chan []byte) { - tun.core = core + tun.Adapter.init(core, send, recv) tun.icmpv6.init(tun) - tun.send = send - tun.recv = recv } // Starts the setup process for the TUN/TAP adapter, and if successful, starts From d5031a5cb610cd755039fbf68d013418f77fcb74 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 00:48:27 +0000 Subject: [PATCH 20/30] Metadata exchange without sessions --- src/yggdrasil/admin.go | 52 +++++++++++++++ src/yggdrasil/core.go | 13 ++-- src/yggdrasil/metadata.go | 92 ++++++++++++++++++++++++++ src/yggdrasil/router.go | 2 +- src/yggdrasil/session.go | 136 +++++++++----------------------------- src/yggdrasil/wire.go | 5 +- 6 files changed, 187 insertions(+), 113 deletions(-) create mode 100644 src/yggdrasil/metadata.go diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 266d5a8..1bf6af0 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -322,6 +322,14 @@ func (a *admin) init(c *Core, listenaddr string) { return admin_info{}, err } }) + a.addHandler("getMeta", []string{"box_pub_key", "coords"}, func(in admin_info) (admin_info, error) { + result, err := a.admin_getMeta(in["box_pub_key"].(string), in["coords"].(string)) + if err == nil { + return admin_info{"metadata": string(result)}, nil + } else { + return admin_info{}, err + } + }) } // start runs the admin API socket to listen for / respond to admin API calls. @@ -806,6 +814,50 @@ func (a *admin) admin_dhtPing(keyString, coordString, targetString string) (dhtR return dhtRes{}, errors.New(fmt.Sprintf("DHT ping timeout: %s", keyString)) } +func (a *admin) admin_getMeta(keyString, coordString string) (metadataPayload, error) { + var key boxPubKey + if keyBytes, err := hex.DecodeString(keyString); err != nil { + return metadataPayload{}, err + } else { + copy(key[:], keyBytes) + } + var coords []byte + for _, cstr := range strings.Split(strings.Trim(coordString, "[]"), " ") { + if cstr == "" { + // Special case, happens if trimmed is the empty string, e.g. this is the root + continue + } + if u64, err := strconv.ParseUint(cstr, 10, 8); err != nil { + return metadataPayload{}, err + } else { + coords = append(coords, uint8(u64)) + } + } + response := make(chan *metadataPayload, 1) + sendMetaRequest := func() { + a.core.metadata.callbacks[key] = metadataCallback{ + created: time.Now(), + call: func(meta *metadataPayload) { + defer func() { recover() }() + select { + case response <- meta: + default: + } + }, + } + a.core.metadata.sendMetadata(key, coords, false) + } + a.core.router.doAdmin(sendMetaRequest) + go func() { + time.Sleep(6 * time.Second) + close(response) + }() + for res := range response { + return *res, nil + } + return metadataPayload{}, errors.New(fmt.Sprintf("getMeta timeout: %s", keyString)) +} + // getResponse_dot returns a response for a graphviz dot formatted representation of the known parts of the network. // This is color-coded and labeled, and includes the self node, switch peers, nodes known to the DHT, and nodes with open sessions. // The graph is structured as a tree with directed links leading away from the root. diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 72a11d7..7a3564d 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -32,6 +32,7 @@ type Core struct { admin admin searches searches multicast multicast + metadata metadata tcp tcpInterface log *log.Logger ifceExpr []*regexp.Regexp // the zone of link-local IPv6 peers must match this @@ -124,6 +125,9 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { c.init(&boxPub, &boxPriv, &sigPub, &sigPriv) c.admin.init(c, nc.AdminListen) + c.metadata.init(c) + c.metadata.setMetadata(metadataPayload("HIYA, THIS IS METADATA")) + if err := c.tcp.init(c, nc.Listen, nc.ReadTimeout); err != nil { c.log.Println("Failed to start TCP interface") return err @@ -138,7 +142,6 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { return err } - c.sessions.setMetadata(metadata("HIYA, THIS IS METADATA")) c.sessions.setSessionFirewallState(nc.SessionFirewall.Enable) c.sessions.setSessionFirewallDefaults( nc.SessionFirewall.AllowFromDirect, @@ -241,13 +244,13 @@ func (c *Core) GetSubnet() *net.IPNet { } // Gets the node metadata. -func (c *Core) GetMetadata() metadata { - return c.sessions.getMetadata() +func (c *Core) GetMetadata() metadataPayload { + return c.metadata.getMetadata() } // Sets the node metadata. -func (c *Core) SetMetadata(meta metadata) { - c.sessions.setMetadata(meta) +func (c *Core) SetMetadata(meta metadataPayload) { + c.metadata.setMetadata(meta) } // Sets the output logger of the Yggdrasil node after startup. This may be diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go new file mode 100644 index 0000000..7f607ed --- /dev/null +++ b/src/yggdrasil/metadata.go @@ -0,0 +1,92 @@ +package yggdrasil + +import ( + "sync" + "time" +) + +type metadata struct { + core *Core + myMetadata metadataPayload + myMetadataMutex sync.RWMutex + callbacks map[boxPubKey]metadataCallback + cache map[boxPubKey]metadataPayload +} + +type metadataPayload []byte + +type metadataCallback struct { + call func(meta *metadataPayload) + created time.Time +} + +// Initialises the metadata cache/callback stuff +func (m *metadata) init(core *Core) { + m.core = core + m.callbacks = make(map[boxPubKey]metadataCallback) + m.cache = make(map[boxPubKey]metadataPayload) + + go func() { + for { + for boxPubKey, callback := range m.callbacks { + if time.Since(callback.created) > time.Minute { + delete(m.callbacks, boxPubKey) + } + } + time.Sleep(time.Second * 5) + } + }() +} + +// Handles the callback, if there is one +func (m *metadata) callback(sender boxPubKey, meta metadataPayload) { + if callback, ok := m.callbacks[sender]; ok { + callback.call(&meta) + delete(m.callbacks, sender) + } +} + +// Get the metadata +func (m *metadata) getMetadata() metadataPayload { + m.myMetadataMutex.RLock() + defer m.myMetadataMutex.RUnlock() + return m.myMetadata +} + +// Set the metadata +func (m *metadata) setMetadata(meta metadataPayload) { + m.myMetadataMutex.Lock() + defer m.myMetadataMutex.Unlock() + m.myMetadata = meta +} + +// Handles a meta request/response. +func (m *metadata) handleMetadata(meta *sessionMeta) { + if meta.IsResponse { + m.core.metadata.callback(meta.SendPermPub, meta.Metadata) + } else { + m.sendMetadata(meta.SendPermPub, meta.SendCoords, true) + } +} + +// Send metadata request or response +func (m *metadata) sendMetadata(key boxPubKey, coords []byte, isResponse bool) { + table := m.core.switchTable.table.Load().(lookupTable) + meta := sessionMeta{ + SendCoords: table.self.getCoords(), + IsResponse: isResponse, + Metadata: m.core.metadata.getMetadata(), + } + bs := meta.encode() + shared := m.core.sessions.getSharedKey(&m.core.boxPriv, &key) + payload, nonce := boxSeal(shared, bs, nil) + p := wire_protoTrafficPacket{ + Coords: coords, + ToKey: key, + FromKey: m.core.boxPub, + Nonce: *nonce, + Payload: payload, + } + packet := p.encode() + m.core.router.out(packet) +} diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index 4914a6b..e6f6b0f 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -483,7 +483,7 @@ func (r *router) handleMetadata(bs []byte, fromKey *boxPubKey) { return } req.SendPermPub = *fromKey - r.core.sessions.handleMetadata(&req) + r.core.metadata.handleMetadata(&req) } // Passed a function to call. diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index 31fe375..418c46a 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -7,44 +7,40 @@ package yggdrasil import ( "bytes" "encoding/hex" - "sync" "time" ) // All the information we know about an active session. // This includes coords, permanent and ephemeral keys, handles and nonces, various sorts of timing information for timeout and maintenance, and some metadata for the admin API. type sessionInfo struct { - core *Core - theirAddr address - theirSubnet subnet - theirPermPub boxPubKey - theirSesPub boxPubKey - mySesPub boxPubKey - mySesPriv boxPrivKey - sharedSesKey boxSharedKey // derived from session keys - theirHandle handle - myHandle handle - theirNonce boxNonce - myNonce boxNonce - metaReqTime time.Time - metaResTime time.Time - theirMetadata metadata - theirMTU uint16 - myMTU uint16 - wasMTUFixed bool // Was the MTU fixed by a receive error? - time time.Time // Time we last received a packet - coords []byte // coords of destination - packet []byte // a buffered packet, sent immediately on ping/pong - init bool // Reset if coords change - send chan []byte - recv chan *wire_trafficPacket - nonceMask uint64 - tstamp int64 // tstamp from their last session ping, replay attack mitigation - mtuTime time.Time // time myMTU was last changed - pingTime time.Time // time the first ping was sent since the last received packet - pingSend time.Time // time the last ping was sent - bytesSent uint64 // Bytes of real traffic sent in this session - bytesRecvd uint64 // Bytes of real traffic received in this session + core *Core + theirAddr address + theirSubnet subnet + theirPermPub boxPubKey + theirSesPub boxPubKey + mySesPub boxPubKey + mySesPriv boxPrivKey + sharedSesKey boxSharedKey // derived from session keys + theirHandle handle + myHandle handle + theirNonce boxNonce + myNonce boxNonce + theirMTU uint16 + myMTU uint16 + wasMTUFixed bool // Was the MTU fixed by a receive error? + time time.Time // Time we last received a packet + coords []byte // coords of destination + packet []byte // a buffered packet, sent immediately on ping/pong + init bool // Reset if coords change + send chan []byte + recv chan *wire_trafficPacket + nonceMask uint64 + tstamp int64 // tstamp from their last session ping, replay attack mitigation + mtuTime time.Time // time myMTU was last changed + pingTime time.Time // time the first ping was sent since the last received packet + pingSend time.Time // time the last ping was sent + bytesSent uint64 // Bytes of real traffic sent in this session + bytesRecvd uint64 // Bytes of real traffic received in this session } // Represents a session ping/pong packet, andincludes information like public keys, a session handle, coords, a timestamp to prevent replays, and the tun/tap MTU. @@ -61,12 +57,11 @@ type sessionPing struct { // Represents a session metadata packet. type sessionMeta struct { SendPermPub boxPubKey // Sender's permanent key + SendCoords []byte // Sender's coords IsResponse bool - Metadata metadata + Metadata metadataPayload } -type metadata []byte - // Updates session info in response to a ping, after checking that the ping is OK. // Returns true if the session was updated, or false otherwise. func (s *sessionInfo) update(p *sessionPing) bool { @@ -128,9 +123,6 @@ type sessions struct { sessionFirewallAlwaysAllowsOutbound bool sessionFirewallWhitelist []string sessionFirewallBlacklist []string - // Metadata for this node - myMetadata metadata - myMetadataMutex sync.RWMutex } // Initializes the session struct. @@ -145,20 +137,6 @@ func (ss *sessions) init(core *Core) { ss.lastCleanup = time.Now() } -// Get the metadata -func (ss *sessions) getMetadata() metadata { - ss.myMetadataMutex.RLock() - defer ss.myMetadataMutex.RUnlock() - return ss.myMetadata -} - -// Set the metadata -func (ss *sessions) setMetadata(meta metadata) { - ss.myMetadataMutex.Lock() - defer ss.myMetadataMutex.Unlock() - ss.myMetadata = meta -} - // Enable or disable the session firewall func (ss *sessions) setSessionFirewallState(enabled bool) { ss.sessionFirewallEnabled = enabled @@ -496,60 +474,6 @@ func (ss *sessions) handlePing(ping *sessionPing) { bs, sinfo.packet = sinfo.packet, nil ss.core.router.sendPacket(bs) } - // This requests metadata from the remote side fairly quickly after - // establishing the session, and if other time constraints apply (no more - // often than 15 minutes since receiving the last metadata) - //if time.Since(sinfo.metaResTime).Minutes() > 15 { - // if time.Since(sinfo.metaReqTime).Minutes() > 1 { - // ss.sendMetadata(sinfo, false) - // } - //} -} - -func (ss *sessions) sendMetadata(sinfo *sessionInfo, isResponse bool) { - ss.myMetadataMutex.RLock() - meta := sessionMeta{ - IsResponse: isResponse, - Metadata: ss.myMetadata, - } - ss.myMetadataMutex.RUnlock() - bs := meta.encode() - shared := ss.getSharedKey(&ss.core.boxPriv, &sinfo.theirPermPub) - payload, nonce := boxSeal(shared, bs, nil) - p := wire_protoTrafficPacket{ - Coords: sinfo.coords, - ToKey: sinfo.theirPermPub, - FromKey: ss.core.boxPub, - Nonce: *nonce, - Payload: payload, - } - packet := p.encode() - ss.core.router.out(packet) - if !isResponse { - sinfo.metaReqTime = time.Now() - } -} - -// Handles a meta request/response. -func (ss *sessions) handleMetadata(meta *sessionMeta) { - // Get the corresponding session (or create a new session) - sinfo, isIn := ss.getByTheirPerm(&meta.SendPermPub) - // Check the session firewall - if !isIn && ss.sessionFirewallEnabled { - if !ss.isSessionAllowed(&meta.SendPermPub, false) { - return - } - } - if !isIn || sinfo.timedout() { - return - } - if meta.IsResponse { - sinfo.theirMetadata = meta.Metadata - sinfo.metaResTime = time.Now() - - } else { - ss.sendMetadata(sinfo, true) - } } // Used to subtract one nonce from another, staying in the range +- 64. diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index 2d87a37..d46994d 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -364,6 +364,7 @@ func (p *sessionMeta) encode() []byte { pTypeVal = wire_SessionMetaRequest } bs := wire_encode_uint64(pTypeVal) + bs = wire_put_coords(p.SendCoords, bs) if pTypeVal == wire_SessionMetaResponse { bs = append(bs, p.Metadata...) } @@ -378,12 +379,14 @@ func (p *sessionMeta) decode(bs []byte) bool { return false case pType != wire_SessionMetaRequest && pType != wire_SessionMetaResponse: return false + case !wire_chop_coords(&p.SendCoords, &bs): + return false } if p.IsResponse = pType == wire_SessionMetaResponse; p.IsResponse { if len(bs) == 0 { return false } - p.Metadata = make(metadata, len(bs)) + p.Metadata = make(metadataPayload, len(bs)) if !wire_chop_slice(p.Metadata[:], &bs) { return false } From 8b63e841ea27dc74c1216c9b03a5c21375229589 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 10:39:31 +0000 Subject: [PATCH 21/30] Make threadsafe, add cache --- src/yggdrasil/admin.go | 17 +++++++---------- src/yggdrasil/metadata.go | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index e773630..7c9ed1b 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -829,16 +829,13 @@ func (a *admin) admin_getMeta(keyString, coordString string) (metadataPayload, e } response := make(chan *metadataPayload, 1) sendMetaRequest := func() { - a.core.metadata.callbacks[key] = metadataCallback{ - created: time.Now(), - call: func(meta *metadataPayload) { - defer func() { recover() }() - select { - case response <- meta: - default: - } - }, - } + a.core.metadata.addCallback(key, func(meta *metadataPayload) { + defer func() { recover() }() + select { + case response <- meta: + default: + } + }) a.core.metadata.sendMetadata(key, coords, false) } a.core.router.doAdmin(sendMetaRequest) diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go index 7f607ed..19393b1 100644 --- a/src/yggdrasil/metadata.go +++ b/src/yggdrasil/metadata.go @@ -10,7 +10,9 @@ type metadata struct { myMetadata metadataPayload myMetadataMutex sync.RWMutex callbacks map[boxPubKey]metadataCallback + callbacksMutex sync.Mutex cache map[boxPubKey]metadataPayload + cacheMutex sync.RWMutex } type metadataPayload []byte @@ -38,8 +40,20 @@ func (m *metadata) init(core *Core) { }() } +// Add a callback +func (m *metadata) addCallback(sender boxPubKey, call func(meta *metadataPayload)) { + m.callbacksMutex.Lock() + defer m.callbacksMutex.Unlock() + m.callbacks[sender] = metadataCallback{ + created: time.Now(), + call: call, + } +} + // Handles the callback, if there is one func (m *metadata) callback(sender boxPubKey, meta metadataPayload) { + m.callbacksMutex.Lock() + defer m.callbacksMutex.Unlock() if callback, ok := m.callbacks[sender]; ok { callback.call(&meta) delete(m.callbacks, sender) @@ -60,10 +74,28 @@ func (m *metadata) setMetadata(meta metadataPayload) { m.myMetadata = meta } +// Add metadata into the cache for a node +func (m *metadata) addCachedMetadata(key boxPubKey, payload metadataPayload) { + m.cacheMutex.Lock() + defer m.cacheMutex.Unlock() + m.cache[key] = payload +} + +// Get a metadata entry from the cache +func (m *metadata) getCachedMetadata(key boxPubKey) metadataPayload { + m.cacheMutex.RLock() + defer m.cacheMutex.RUnlock() + if meta, ok := m.cache[key]; ok { + return meta + } + return metadataPayload{} +} + // Handles a meta request/response. func (m *metadata) handleMetadata(meta *sessionMeta) { if meta.IsResponse { - m.core.metadata.callback(meta.SendPermPub, meta.Metadata) + m.callback(meta.SendPermPub, meta.Metadata) + m.addCachedMetadata(meta.SendPermPub, meta.Metadata) } else { m.sendMetadata(meta.SendPermPub, meta.SendCoords, true) } From d07e0ddfa0419c4dbba249e6f1eb29ec12c13aa2 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 10:56:46 +0000 Subject: [PATCH 22/30] Default metadata --- src/yggdrasil/admin.go | 7 ++++++- src/yggdrasil/core.go | 12 +++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 7c9ed1b..d78499e 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -325,7 +325,12 @@ func (a *admin) init(c *Core, listenaddr string) { a.addHandler("getMeta", []string{"box_pub_key", "coords"}, func(in admin_info) (admin_info, error) { result, err := a.admin_getMeta(in["box_pub_key"].(string), in["coords"].(string)) if err == nil { - return admin_info{"metadata": string(result)}, nil + var m map[string]interface{} + if err = json.Unmarshal(result, &m); err == nil { + return admin_info{"metadata": m}, nil + } else { + return admin_info{}, err + } } else { return admin_info{}, err } diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 559997f..85c5540 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -2,11 +2,13 @@ package yggdrasil import ( "encoding/hex" + "encoding/json" "fmt" "io/ioutil" "log" "net" "regexp" + "runtime" "github.com/yggdrasil-network/yggdrasil-go/src/config" "github.com/yggdrasil-network/yggdrasil-go/src/defaults" @@ -124,7 +126,15 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { c.admin.init(c, nc.AdminListen) c.metadata.init(c) - c.metadata.setMetadata(metadataPayload("HIYA, THIS IS METADATA")) + m := map[string]string{ + "buildname": GetBuildName(), + "buildversion": GetBuildVersion(), + "buildplatform": runtime.GOOS, + "buildarch": runtime.GOARCH, + } + if json, err := json.Marshal(m); err == nil { + c.metadata.setMetadata(json) + } if err := c.tcp.init(c, nc.Listen, nc.ReadTimeout); err != nil { c.log.Println("Failed to start TCP interface") From d9884a5cac8cc3008b4f348a895c49354d05d9ae Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 11:15:48 +0000 Subject: [PATCH 23/30] Make use of metadata cache --- src/yggdrasil/admin.go | 15 ++++++++++--- src/yggdrasil/metadata.go | 45 ++++++++++++++++++++++++++++----------- 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index d78499e..2fba594 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -322,8 +322,12 @@ func (a *admin) init(c *Core, listenaddr string) { return admin_info{}, err } }) - a.addHandler("getMeta", []string{"box_pub_key", "coords"}, func(in admin_info) (admin_info, error) { - result, err := a.admin_getMeta(in["box_pub_key"].(string), in["coords"].(string)) + a.addHandler("getMeta", []string{"box_pub_key", "coords", "[nocache]"}, func(in admin_info) (admin_info, error) { + var nocache bool + if in["nocache"] != nil { + nocache = in["nocache"].(string) == "true" + } + result, err := a.admin_getMeta(in["box_pub_key"].(string), in["coords"].(string), nocache) if err == nil { var m map[string]interface{} if err = json.Unmarshal(result, &m); err == nil { @@ -813,13 +817,18 @@ func (a *admin) admin_dhtPing(keyString, coordString, targetString string) (dhtR return dhtRes{}, errors.New(fmt.Sprintf("DHT ping timeout: %s", keyString)) } -func (a *admin) admin_getMeta(keyString, coordString string) (metadataPayload, error) { +func (a *admin) admin_getMeta(keyString, coordString string, nocache bool) (metadataPayload, error) { var key boxPubKey if keyBytes, err := hex.DecodeString(keyString); err != nil { return metadataPayload{}, err } else { copy(key[:], keyBytes) } + if !nocache { + if response, err := a.core.metadata.getCachedMetadata(key); err == nil { + return response, nil + } + } var coords []byte for _, cstr := range strings.Split(strings.Trim(coordString, "[]"), " ") { if cstr == "" { diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go index 19393b1..4acd467 100644 --- a/src/yggdrasil/metadata.go +++ b/src/yggdrasil/metadata.go @@ -1,6 +1,7 @@ package yggdrasil import ( + "errors" "sync" "time" ) @@ -11,36 +12,51 @@ type metadata struct { myMetadataMutex sync.RWMutex callbacks map[boxPubKey]metadataCallback callbacksMutex sync.Mutex - cache map[boxPubKey]metadataPayload + cache map[boxPubKey]metadataCached cacheMutex sync.RWMutex } type metadataPayload []byte +type metadataCached struct { + payload metadataPayload + created time.Time +} + type metadataCallback struct { call func(meta *metadataPayload) created time.Time } -// Initialises the metadata cache/callback stuff +// Initialises the metadata cache/callback maps, and starts a goroutine to keep +// the cache/callback maps clean of stale entries func (m *metadata) init(core *Core) { m.core = core m.callbacks = make(map[boxPubKey]metadataCallback) - m.cache = make(map[boxPubKey]metadataPayload) + m.cache = make(map[boxPubKey]metadataCached) go func() { for { + m.callbacksMutex.Lock() for boxPubKey, callback := range m.callbacks { if time.Since(callback.created) > time.Minute { delete(m.callbacks, boxPubKey) } } - time.Sleep(time.Second * 5) + m.callbacksMutex.Unlock() + m.cacheMutex.Lock() + for boxPubKey, cache := range m.cache { + if time.Since(cache.created) > time.Hour { + delete(m.cache, boxPubKey) + } + } + m.cacheMutex.Unlock() + time.Sleep(time.Second * 30) } }() } -// Add a callback +// Add a callback for a metadata lookup func (m *metadata) addCallback(sender boxPubKey, call func(meta *metadataPayload)) { m.callbacksMutex.Lock() defer m.callbacksMutex.Unlock() @@ -60,14 +76,14 @@ func (m *metadata) callback(sender boxPubKey, meta metadataPayload) { } } -// Get the metadata +// Get the current node's metadata func (m *metadata) getMetadata() metadataPayload { m.myMetadataMutex.RLock() defer m.myMetadataMutex.RUnlock() return m.myMetadata } -// Set the metadata +// Set the current node's metadata func (m *metadata) setMetadata(meta metadataPayload) { m.myMetadataMutex.Lock() defer m.myMetadataMutex.Unlock() @@ -78,20 +94,23 @@ func (m *metadata) setMetadata(meta metadataPayload) { func (m *metadata) addCachedMetadata(key boxPubKey, payload metadataPayload) { m.cacheMutex.Lock() defer m.cacheMutex.Unlock() - m.cache[key] = payload + m.cache[key] = metadataCached{ + created: time.Now(), + payload: payload, + } } // Get a metadata entry from the cache -func (m *metadata) getCachedMetadata(key boxPubKey) metadataPayload { +func (m *metadata) getCachedMetadata(key boxPubKey) (metadataPayload, error) { m.cacheMutex.RLock() defer m.cacheMutex.RUnlock() if meta, ok := m.cache[key]; ok { - return meta + return meta.payload, nil } - return metadataPayload{} + return metadataPayload{}, errors.New("No cache entry found") } -// Handles a meta request/response. +// Handles a meta request/response - called from the router func (m *metadata) handleMetadata(meta *sessionMeta) { if meta.IsResponse { m.callback(meta.SendPermPub, meta.Metadata) @@ -101,7 +120,7 @@ func (m *metadata) handleMetadata(meta *sessionMeta) { } } -// Send metadata request or response +// Send metadata request or response - called from the router func (m *metadata) sendMetadata(key boxPubKey, coords []byte, isResponse bool) { table := m.core.switchTable.table.Load().(lookupTable) meta := sessionMeta{ From 92bb63f1964c6fe4e516bdc1993b199a4f459c19 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 11:38:51 +0000 Subject: [PATCH 24/30] Use metadata from config file --- src/config/config.go | 36 ++++++++++++++++++------------------ src/yggdrasil/core.go | 12 +----------- src/yggdrasil/metadata.go | 25 +++++++++++++++++++++++-- 3 files changed, 42 insertions(+), 31 deletions(-) diff --git a/src/config/config.go b/src/config/config.go index 66de668..a4cd5c3 100644 --- a/src/config/config.go +++ b/src/config/config.go @@ -2,24 +2,24 @@ 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\nTCP connections over IPv4 and IPv6 with a random port."` - AdminListen string `comment:"Listen address for admin connections. Default is to listen for local\nconnections either on TCP/9001 or a UNIX socket depending on your\nplatform. Use this value for yggdrasilctl -endpoint=X. To disable\nthe admin socket, use the value \"none\" instead."` - Peers []string `comment:"List of connection strings for static peers in URI format, e.g.\ntcp://a.b.c.d:e or socks://a.b.c.d:e/f.g.h.i:j."` - InterfacePeers map[string][]string `comment:"List of connection strings for static peers in URI format, arranged\nby source interface, e.g. { \"eth0\": [ tcp://a.b.c.d:e ] }. Note that\nSOCKS peerings will NOT be affected by this option and should go in\nthe \"Peers\" section instead."` - ReadTimeout int32 `comment:"Read timeout for connections, specified in milliseconds. If less\nthan 6000 and not negative, 6000 (the default) is used. If negative,\nreads won't time out."` - AllowedEncryptionPublicKeys []string `comment:"List of peer encryption public keys to allow or incoming TCP\nconnections from. If left empty/undefined then all connections\nwill 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."` - SessionFirewall SessionFirewall `comment:"The session firewall controls who can send/receive network traffic\nto/from. This is useful if you want to protect this node without\nresorting to using a real firewall. This does not affect traffic\nbeing routed via this node to somewhere else. Rules are prioritised as\nfollows: blacklist, whitelist, always allow outgoing, direct, remote."` - TunnelRouting TunnelRouting `comment:"Allow tunneling non-Yggdrasil traffic over Yggdrasil. This effectively\nallows you to use Yggdrasil to route to, or to bridge other networks,\nsimilar to a VPN tunnel. Tunnelling works between any two nodes and\ndoes not require them to be directly peered."` - SwitchOptions SwitchOptions `comment:"Advanced options for tuning the switch. Normally you will not need\nto edit these options."` - Metadata interface{} `comment:"Optional node metadata. Entirely optional but visible to all\npeers and nodes with open sessions."` + Listen string `comment:"Listen address for peer connections. Default is to listen for all\nTCP connections over IPv4 and IPv6 with a random port."` + AdminListen string `comment:"Listen address for admin connections. Default is to listen for local\nconnections either on TCP/9001 or a UNIX socket depending on your\nplatform. Use this value for yggdrasilctl -endpoint=X. To disable\nthe admin socket, use the value \"none\" instead."` + Peers []string `comment:"List of connection strings for static peers in URI format, e.g.\ntcp://a.b.c.d:e or socks://a.b.c.d:e/f.g.h.i:j."` + InterfacePeers map[string][]string `comment:"List of connection strings for static peers in URI format, arranged\nby source interface, e.g. { \"eth0\": [ tcp://a.b.c.d:e ] }. Note that\nSOCKS peerings will NOT be affected by this option and should go in\nthe \"Peers\" section instead."` + ReadTimeout int32 `comment:"Read timeout for connections, specified in milliseconds. If less\nthan 6000 and not negative, 6000 (the default) is used. If negative,\nreads won't time out."` + AllowedEncryptionPublicKeys []string `comment:"List of peer encryption public keys to allow or incoming TCP\nconnections from. If left empty/undefined then all connections\nwill 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."` + SessionFirewall SessionFirewall `comment:"The session firewall controls who can send/receive network traffic\nto/from. This is useful if you want to protect this node without\nresorting to using a real firewall. This does not affect traffic\nbeing routed via this node to somewhere else. Rules are prioritised as\nfollows: blacklist, whitelist, always allow outgoing, direct, remote."` + TunnelRouting TunnelRouting `comment:"Allow tunneling non-Yggdrasil traffic over Yggdrasil. This effectively\nallows you to use Yggdrasil to route to, or to bridge other networks,\nsimilar to a VPN tunnel. Tunnelling works between any two nodes and\ndoes not require them to be directly peered."` + SwitchOptions SwitchOptions `comment:"Advanced options for tuning the switch. Normally you will not need\nto edit these options."` + Metadata map[string]interface{} `comment:"Optional node metadata. This must be a { \"key\": \"value\", ... } map\nor set as null. This is entirely optional but, if set, is visible\nto the whole network on request."` //Net NetConfig `comment:"Extended options for connecting to peers over other networks."` } diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 85c5540..5fbedc8 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -2,13 +2,11 @@ package yggdrasil import ( "encoding/hex" - "encoding/json" "fmt" "io/ioutil" "log" "net" "regexp" - "runtime" "github.com/yggdrasil-network/yggdrasil-go/src/config" "github.com/yggdrasil-network/yggdrasil-go/src/defaults" @@ -126,15 +124,7 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { c.admin.init(c, nc.AdminListen) c.metadata.init(c) - m := map[string]string{ - "buildname": GetBuildName(), - "buildversion": GetBuildVersion(), - "buildplatform": runtime.GOOS, - "buildarch": runtime.GOARCH, - } - if json, err := json.Marshal(m); err == nil { - c.metadata.setMetadata(json) - } + c.metadata.setMetadata(nc.Metadata) if err := c.tcp.init(c, nc.Listen, nc.ReadTimeout); err != nil { c.log.Println("Failed to start TCP interface") diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go index 4acd467..7deb60d 100644 --- a/src/yggdrasil/metadata.go +++ b/src/yggdrasil/metadata.go @@ -1,7 +1,9 @@ package yggdrasil import ( + "encoding/json" "errors" + "runtime" "sync" "time" ) @@ -84,10 +86,29 @@ func (m *metadata) getMetadata() metadataPayload { } // Set the current node's metadata -func (m *metadata) setMetadata(meta metadataPayload) { +func (m *metadata) setMetadata(given interface{}) error { m.myMetadataMutex.Lock() defer m.myMetadataMutex.Unlock() - m.myMetadata = meta + newmeta := map[string]interface{}{ + "buildname": GetBuildName(), + "buildversion": GetBuildVersion(), + "buildplatform": runtime.GOOS, + "buildarch": runtime.GOARCH, + } + if metamap, ok := given.(map[string]interface{}); ok { + for key, value := range metamap { + if _, ok := newmeta[key]; ok { + continue + } + newmeta[key] = value + } + } + if newjson, err := json.Marshal(newmeta); err == nil { + m.myMetadata = newjson + return nil + } else { + return err + } } // Add metadata into the cache for a node From 98a544fd7dc9b63e05ebed97416488016e61e268 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 11:48:43 +0000 Subject: [PATCH 25/30] Fix bug in yggdrasilctl where -endpoint gets ignored --- cmd/yggdrasilctl/main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/yggdrasilctl/main.go b/cmd/yggdrasilctl/main.go index b37c256..8135815 100644 --- a/cmd/yggdrasilctl/main.go +++ b/cmd/yggdrasilctl/main.go @@ -87,6 +87,7 @@ func main() { logger.Println("Falling back to platform default", defaults.GetDefaults().DefaultAdminListen) } } else { + endpoint = *server logger.Println("Using endpoint", endpoint, "from command line") } From a50964b334d37b39082c201e75193e52a2f96fbc Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 11:57:25 +0000 Subject: [PATCH 26/30] Fix panic if Peers or InterfacePeers is commented out --- cmd/yggdrasil/main.go | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/cmd/yggdrasil/main.go b/cmd/yggdrasil/main.go index ee5375b..d93f5d2 100644 --- a/cmd/yggdrasil/main.go +++ b/cmd/yggdrasil/main.go @@ -191,19 +191,8 @@ func main() { } // Check to see if the peers are in a parsable format, if not then default // them to the TCP scheme - for index, peer := range dat["Peers"].([]interface{}) { - uri := peer.(string) - if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { - continue - } - if strings.HasPrefix(uri, "tcp:") { - uri = uri[4:] - } - (dat["Peers"].([]interface{}))[index] = "tcp://" + uri - } - // Now do the same with the interface peers - for intf, peers := range dat["InterfacePeers"].(map[string]interface{}) { - for index, peer := range peers.([]interface{}) { + if peers, ok := dat["Peers"].([]interface{}); ok { + for index, peer := range peers { uri := peer.(string) if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { continue @@ -211,7 +200,22 @@ func main() { if strings.HasPrefix(uri, "tcp:") { uri = uri[4:] } - ((dat["InterfacePeers"].(map[string]interface{}))[intf]).([]interface{})[index] = "tcp://" + uri + (dat["Peers"].([]interface{}))[index] = "tcp://" + uri + } + } + // Now do the same with the interface peers + if interfacepeers, ok := dat["InterfacePeers"].(map[string]interface{}); ok { + for intf, peers := range interfacepeers { + for index, peer := range peers.([]interface{}) { + uri := peer.(string) + if strings.HasPrefix(uri, "tcp://") || strings.HasPrefix(uri, "socks://") { + continue + } + if strings.HasPrefix(uri, "tcp:") { + uri = uri[4:] + } + ((dat["InterfacePeers"].(map[string]interface{}))[intf]).([]interface{})[index] = "tcp://" + uri + } } } // Overlay our newly mapped configuration onto the autoconf node config that From 9a5cf96c298025c84f710ec0c7be1fdc7e71fc39 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 12:18:52 +0000 Subject: [PATCH 27/30] Rename admin socket getMeta to getMetadata --- src/yggdrasil/admin.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 2fba594..5def7e0 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -322,12 +322,12 @@ func (a *admin) init(c *Core, listenaddr string) { return admin_info{}, err } }) - a.addHandler("getMeta", []string{"box_pub_key", "coords", "[nocache]"}, func(in admin_info) (admin_info, error) { + a.addHandler("getMetadata", []string{"box_pub_key", "coords", "[nocache]"}, func(in admin_info) (admin_info, error) { var nocache bool if in["nocache"] != nil { nocache = in["nocache"].(string) == "true" } - result, err := a.admin_getMeta(in["box_pub_key"].(string), in["coords"].(string), nocache) + result, err := a.admin_getMetadata(in["box_pub_key"].(string), in["coords"].(string), nocache) if err == nil { var m map[string]interface{} if err = json.Unmarshal(result, &m); err == nil { @@ -817,7 +817,7 @@ func (a *admin) admin_dhtPing(keyString, coordString, targetString string) (dhtR return dhtRes{}, errors.New(fmt.Sprintf("DHT ping timeout: %s", keyString)) } -func (a *admin) admin_getMeta(keyString, coordString string, nocache bool) (metadataPayload, error) { +func (a *admin) admin_getMetadata(keyString, coordString string, nocache bool) (metadataPayload, error) { var key boxPubKey if keyBytes, err := hex.DecodeString(keyString); err != nil { return metadataPayload{}, err @@ -860,7 +860,7 @@ func (a *admin) admin_getMeta(keyString, coordString string, nocache bool) (meta for res := range response { return *res, nil } - return metadataPayload{}, errors.New(fmt.Sprintf("getMeta timeout: %s", keyString)) + return metadataPayload{}, errors.New(fmt.Sprintf("getMetadata timeout: %s", keyString)) } // getResponse_dot returns a response for a graphviz dot formatted representation of the known parts of the network. From 07c26176b6272b4c3df8721397f214febeef5167 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 12:21:00 +0000 Subject: [PATCH 28/30] Fix core.SetMetadata --- src/yggdrasil/core.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 5fbedc8..05d528a 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -247,7 +247,7 @@ func (c *Core) GetMetadata() metadataPayload { } // Sets the node metadata. -func (c *Core) SetMetadata(meta metadataPayload) { +func (c *Core) SetMetadata(meta interface{}) { c.metadata.setMetadata(meta) } From 226c72df16f6811d45413627524b2728216bfcb3 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 13:18:35 +0000 Subject: [PATCH 29/30] Set max metadata size to 16kb --- src/yggdrasil/metadata.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go index 7deb60d..67bab4a 100644 --- a/src/yggdrasil/metadata.go +++ b/src/yggdrasil/metadata.go @@ -104,6 +104,9 @@ func (m *metadata) setMetadata(given interface{}) error { } } if newjson, err := json.Marshal(newmeta); err == nil { + if len(newjson) > 16384 { + return errors.New("Metadata exceeds max length of 16384 bytes") + } m.myMetadata = newjson return nil } else { From e0ff3ca587e8673bdababf23c5b243b2c6901653 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sat, 15 Dec 2018 22:37:11 +0000 Subject: [PATCH 30/30] Rename Metadata to NodeInfo --- src/config/config.go | 2 +- src/yggdrasil/admin.go | 28 +++--- src/yggdrasil/core.go | 18 ++-- src/yggdrasil/metadata.go | 167 ------------------------------------ src/yggdrasil/nodeinfo.go | 175 ++++++++++++++++++++++++++++++++++++++ src/yggdrasil/router.go | 14 +-- src/yggdrasil/session.go | 8 -- src/yggdrasil/wire.go | 28 +++--- 8 files changed, 220 insertions(+), 220 deletions(-) delete mode 100644 src/yggdrasil/metadata.go create mode 100644 src/yggdrasil/nodeinfo.go diff --git a/src/config/config.go b/src/config/config.go index a4cd5c3..b5a1f89 100644 --- a/src/config/config.go +++ b/src/config/config.go @@ -19,7 +19,7 @@ type NodeConfig struct { SessionFirewall SessionFirewall `comment:"The session firewall controls who can send/receive network traffic\nto/from. This is useful if you want to protect this node without\nresorting to using a real firewall. This does not affect traffic\nbeing routed via this node to somewhere else. Rules are prioritised as\nfollows: blacklist, whitelist, always allow outgoing, direct, remote."` TunnelRouting TunnelRouting `comment:"Allow tunneling non-Yggdrasil traffic over Yggdrasil. This effectively\nallows you to use Yggdrasil to route to, or to bridge other networks,\nsimilar to a VPN tunnel. Tunnelling works between any two nodes and\ndoes not require them to be directly peered."` SwitchOptions SwitchOptions `comment:"Advanced options for tuning the switch. Normally you will not need\nto edit these options."` - Metadata map[string]interface{} `comment:"Optional node metadata. This must be a { \"key\": \"value\", ... } map\nor set as null. This is entirely optional but, if set, is visible\nto the whole network on request."` + NodeInfo map[string]interface{} `comment:"Optional node info. This must be a { \"key\": \"value\", ... } map\nor set as null. This is entirely optional but, if set, is visible\nto the whole network on request."` //Net NetConfig `comment:"Extended options for connecting to peers over other networks."` } diff --git a/src/yggdrasil/admin.go b/src/yggdrasil/admin.go index 5def7e0..f3b5998 100644 --- a/src/yggdrasil/admin.go +++ b/src/yggdrasil/admin.go @@ -322,16 +322,16 @@ func (a *admin) init(c *Core, listenaddr string) { return admin_info{}, err } }) - a.addHandler("getMetadata", []string{"box_pub_key", "coords", "[nocache]"}, func(in admin_info) (admin_info, error) { + a.addHandler("getNodeInfo", []string{"box_pub_key", "coords", "[nocache]"}, func(in admin_info) (admin_info, error) { var nocache bool if in["nocache"] != nil { nocache = in["nocache"].(string) == "true" } - result, err := a.admin_getMetadata(in["box_pub_key"].(string), in["coords"].(string), nocache) + result, err := a.admin_getNodeInfo(in["box_pub_key"].(string), in["coords"].(string), nocache) if err == nil { var m map[string]interface{} if err = json.Unmarshal(result, &m); err == nil { - return admin_info{"metadata": m}, nil + return admin_info{"nodeinfo": m}, nil } else { return admin_info{}, err } @@ -817,15 +817,15 @@ func (a *admin) admin_dhtPing(keyString, coordString, targetString string) (dhtR return dhtRes{}, errors.New(fmt.Sprintf("DHT ping timeout: %s", keyString)) } -func (a *admin) admin_getMetadata(keyString, coordString string, nocache bool) (metadataPayload, error) { +func (a *admin) admin_getNodeInfo(keyString, coordString string, nocache bool) (nodeinfoPayload, error) { var key boxPubKey if keyBytes, err := hex.DecodeString(keyString); err != nil { - return metadataPayload{}, err + return nodeinfoPayload{}, err } else { copy(key[:], keyBytes) } if !nocache { - if response, err := a.core.metadata.getCachedMetadata(key); err == nil { + if response, err := a.core.nodeinfo.getCachedNodeInfo(key); err == nil { return response, nil } } @@ -836,23 +836,23 @@ func (a *admin) admin_getMetadata(keyString, coordString string, nocache bool) ( continue } if u64, err := strconv.ParseUint(cstr, 10, 8); err != nil { - return metadataPayload{}, err + return nodeinfoPayload{}, err } else { coords = append(coords, uint8(u64)) } } - response := make(chan *metadataPayload, 1) - sendMetaRequest := func() { - a.core.metadata.addCallback(key, func(meta *metadataPayload) { + response := make(chan *nodeinfoPayload, 1) + sendNodeInfoRequest := func() { + a.core.nodeinfo.addCallback(key, func(nodeinfo *nodeinfoPayload) { defer func() { recover() }() select { - case response <- meta: + case response <- nodeinfo: default: } }) - a.core.metadata.sendMetadata(key, coords, false) + a.core.nodeinfo.sendNodeInfo(key, coords, false) } - a.core.router.doAdmin(sendMetaRequest) + a.core.router.doAdmin(sendNodeInfoRequest) go func() { time.Sleep(6 * time.Second) close(response) @@ -860,7 +860,7 @@ func (a *admin) admin_getMetadata(keyString, coordString string, nocache bool) ( for res := range response { return *res, nil } - return metadataPayload{}, errors.New(fmt.Sprintf("getMetadata timeout: %s", keyString)) + return nodeinfoPayload{}, errors.New(fmt.Sprintf("getNodeInfo timeout: %s", keyString)) } // getResponse_dot returns a response for a graphviz dot formatted representation of the known parts of the network. diff --git a/src/yggdrasil/core.go b/src/yggdrasil/core.go index 05d528a..66c6964 100644 --- a/src/yggdrasil/core.go +++ b/src/yggdrasil/core.go @@ -31,7 +31,7 @@ type Core struct { admin admin searches searches multicast multicast - metadata metadata + nodeinfo nodeinfo tcp tcpInterface log *log.Logger ifceExpr []*regexp.Regexp // the zone of link-local IPv6 peers must match this @@ -123,8 +123,8 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error { c.init(&boxPub, &boxPriv, &sigPub, &sigPriv) c.admin.init(c, nc.AdminListen) - c.metadata.init(c) - c.metadata.setMetadata(nc.Metadata) + c.nodeinfo.init(c) + c.nodeinfo.setNodeInfo(nc.NodeInfo) if err := c.tcp.init(c, nc.Listen, nc.ReadTimeout); err != nil { c.log.Println("Failed to start TCP interface") @@ -241,14 +241,14 @@ func (c *Core) GetSubnet() *net.IPNet { return &net.IPNet{IP: subnet, Mask: net.CIDRMask(64, 128)} } -// Gets the node metadata. -func (c *Core) GetMetadata() metadataPayload { - return c.metadata.getMetadata() +// Gets the nodeinfo. +func (c *Core) GetNodeInfo() nodeinfoPayload { + return c.nodeinfo.getNodeInfo() } -// Sets the node metadata. -func (c *Core) SetMetadata(meta interface{}) { - c.metadata.setMetadata(meta) +// Sets the nodeinfo. +func (c *Core) SetNodeInfo(nodeinfo interface{}) { + c.nodeinfo.setNodeInfo(nodeinfo) } // Sets the output logger of the Yggdrasil node after startup. This may be diff --git a/src/yggdrasil/metadata.go b/src/yggdrasil/metadata.go deleted file mode 100644 index 67bab4a..0000000 --- a/src/yggdrasil/metadata.go +++ /dev/null @@ -1,167 +0,0 @@ -package yggdrasil - -import ( - "encoding/json" - "errors" - "runtime" - "sync" - "time" -) - -type metadata struct { - core *Core - myMetadata metadataPayload - myMetadataMutex sync.RWMutex - callbacks map[boxPubKey]metadataCallback - callbacksMutex sync.Mutex - cache map[boxPubKey]metadataCached - cacheMutex sync.RWMutex -} - -type metadataPayload []byte - -type metadataCached struct { - payload metadataPayload - created time.Time -} - -type metadataCallback struct { - call func(meta *metadataPayload) - created time.Time -} - -// Initialises the metadata cache/callback maps, and starts a goroutine to keep -// the cache/callback maps clean of stale entries -func (m *metadata) init(core *Core) { - m.core = core - m.callbacks = make(map[boxPubKey]metadataCallback) - m.cache = make(map[boxPubKey]metadataCached) - - go func() { - for { - m.callbacksMutex.Lock() - for boxPubKey, callback := range m.callbacks { - if time.Since(callback.created) > time.Minute { - delete(m.callbacks, boxPubKey) - } - } - m.callbacksMutex.Unlock() - m.cacheMutex.Lock() - for boxPubKey, cache := range m.cache { - if time.Since(cache.created) > time.Hour { - delete(m.cache, boxPubKey) - } - } - m.cacheMutex.Unlock() - time.Sleep(time.Second * 30) - } - }() -} - -// Add a callback for a metadata lookup -func (m *metadata) addCallback(sender boxPubKey, call func(meta *metadataPayload)) { - m.callbacksMutex.Lock() - defer m.callbacksMutex.Unlock() - m.callbacks[sender] = metadataCallback{ - created: time.Now(), - call: call, - } -} - -// Handles the callback, if there is one -func (m *metadata) callback(sender boxPubKey, meta metadataPayload) { - m.callbacksMutex.Lock() - defer m.callbacksMutex.Unlock() - if callback, ok := m.callbacks[sender]; ok { - callback.call(&meta) - delete(m.callbacks, sender) - } -} - -// Get the current node's metadata -func (m *metadata) getMetadata() metadataPayload { - m.myMetadataMutex.RLock() - defer m.myMetadataMutex.RUnlock() - return m.myMetadata -} - -// Set the current node's metadata -func (m *metadata) setMetadata(given interface{}) error { - m.myMetadataMutex.Lock() - defer m.myMetadataMutex.Unlock() - newmeta := map[string]interface{}{ - "buildname": GetBuildName(), - "buildversion": GetBuildVersion(), - "buildplatform": runtime.GOOS, - "buildarch": runtime.GOARCH, - } - if metamap, ok := given.(map[string]interface{}); ok { - for key, value := range metamap { - if _, ok := newmeta[key]; ok { - continue - } - newmeta[key] = value - } - } - if newjson, err := json.Marshal(newmeta); err == nil { - if len(newjson) > 16384 { - return errors.New("Metadata exceeds max length of 16384 bytes") - } - m.myMetadata = newjson - return nil - } else { - return err - } -} - -// Add metadata into the cache for a node -func (m *metadata) addCachedMetadata(key boxPubKey, payload metadataPayload) { - m.cacheMutex.Lock() - defer m.cacheMutex.Unlock() - m.cache[key] = metadataCached{ - created: time.Now(), - payload: payload, - } -} - -// Get a metadata entry from the cache -func (m *metadata) getCachedMetadata(key boxPubKey) (metadataPayload, error) { - m.cacheMutex.RLock() - defer m.cacheMutex.RUnlock() - if meta, ok := m.cache[key]; ok { - return meta.payload, nil - } - return metadataPayload{}, errors.New("No cache entry found") -} - -// Handles a meta request/response - called from the router -func (m *metadata) handleMetadata(meta *sessionMeta) { - if meta.IsResponse { - m.callback(meta.SendPermPub, meta.Metadata) - m.addCachedMetadata(meta.SendPermPub, meta.Metadata) - } else { - m.sendMetadata(meta.SendPermPub, meta.SendCoords, true) - } -} - -// Send metadata request or response - called from the router -func (m *metadata) sendMetadata(key boxPubKey, coords []byte, isResponse bool) { - table := m.core.switchTable.table.Load().(lookupTable) - meta := sessionMeta{ - SendCoords: table.self.getCoords(), - IsResponse: isResponse, - Metadata: m.core.metadata.getMetadata(), - } - bs := meta.encode() - shared := m.core.sessions.getSharedKey(&m.core.boxPriv, &key) - payload, nonce := boxSeal(shared, bs, nil) - p := wire_protoTrafficPacket{ - Coords: coords, - ToKey: key, - FromKey: m.core.boxPub, - Nonce: *nonce, - Payload: payload, - } - packet := p.encode() - m.core.router.out(packet) -} diff --git a/src/yggdrasil/nodeinfo.go b/src/yggdrasil/nodeinfo.go new file mode 100644 index 0000000..2146b27 --- /dev/null +++ b/src/yggdrasil/nodeinfo.go @@ -0,0 +1,175 @@ +package yggdrasil + +import ( + "encoding/json" + "errors" + "runtime" + "sync" + "time" +) + +type nodeinfo struct { + core *Core + myNodeInfo nodeinfoPayload + myNodeInfoMutex sync.RWMutex + callbacks map[boxPubKey]nodeinfoCallback + callbacksMutex sync.Mutex + cache map[boxPubKey]nodeinfoCached + cacheMutex sync.RWMutex +} + +type nodeinfoPayload []byte + +type nodeinfoCached struct { + payload nodeinfoPayload + created time.Time +} + +type nodeinfoCallback struct { + call func(nodeinfo *nodeinfoPayload) + created time.Time +} + +// Represents a session nodeinfo packet. +type nodeinfoReqRes struct { + SendPermPub boxPubKey // Sender's permanent key + SendCoords []byte // Sender's coords + IsResponse bool + NodeInfo nodeinfoPayload +} + +// Initialises the nodeinfo cache/callback maps, and starts a goroutine to keep +// the cache/callback maps clean of stale entries +func (m *nodeinfo) init(core *Core) { + m.core = core + m.callbacks = make(map[boxPubKey]nodeinfoCallback) + m.cache = make(map[boxPubKey]nodeinfoCached) + + go func() { + for { + m.callbacksMutex.Lock() + for boxPubKey, callback := range m.callbacks { + if time.Since(callback.created) > time.Minute { + delete(m.callbacks, boxPubKey) + } + } + m.callbacksMutex.Unlock() + m.cacheMutex.Lock() + for boxPubKey, cache := range m.cache { + if time.Since(cache.created) > time.Hour { + delete(m.cache, boxPubKey) + } + } + m.cacheMutex.Unlock() + time.Sleep(time.Second * 30) + } + }() +} + +// Add a callback for a nodeinfo lookup +func (m *nodeinfo) addCallback(sender boxPubKey, call func(nodeinfo *nodeinfoPayload)) { + m.callbacksMutex.Lock() + defer m.callbacksMutex.Unlock() + m.callbacks[sender] = nodeinfoCallback{ + created: time.Now(), + call: call, + } +} + +// Handles the callback, if there is one +func (m *nodeinfo) callback(sender boxPubKey, nodeinfo nodeinfoPayload) { + m.callbacksMutex.Lock() + defer m.callbacksMutex.Unlock() + if callback, ok := m.callbacks[sender]; ok { + callback.call(&nodeinfo) + delete(m.callbacks, sender) + } +} + +// Get the current node's nodeinfo +func (m *nodeinfo) getNodeInfo() nodeinfoPayload { + m.myNodeInfoMutex.RLock() + defer m.myNodeInfoMutex.RUnlock() + return m.myNodeInfo +} + +// Set the current node's nodeinfo +func (m *nodeinfo) setNodeInfo(given interface{}) error { + m.myNodeInfoMutex.Lock() + defer m.myNodeInfoMutex.Unlock() + newnodeinfo := map[string]interface{}{ + "buildname": GetBuildName(), + "buildversion": GetBuildVersion(), + "buildplatform": runtime.GOOS, + "buildarch": runtime.GOARCH, + } + if nodeinfomap, ok := given.(map[string]interface{}); ok { + for key, value := range nodeinfomap { + if _, ok := newnodeinfo[key]; ok { + continue + } + newnodeinfo[key] = value + } + } + if newjson, err := json.Marshal(newnodeinfo); err == nil { + if len(newjson) > 16384 { + return errors.New("NodeInfo exceeds max length of 16384 bytes") + } + m.myNodeInfo = newjson + return nil + } else { + return err + } +} + +// Add nodeinfo into the cache for a node +func (m *nodeinfo) addCachedNodeInfo(key boxPubKey, payload nodeinfoPayload) { + m.cacheMutex.Lock() + defer m.cacheMutex.Unlock() + m.cache[key] = nodeinfoCached{ + created: time.Now(), + payload: payload, + } +} + +// Get a nodeinfo entry from the cache +func (m *nodeinfo) getCachedNodeInfo(key boxPubKey) (nodeinfoPayload, error) { + m.cacheMutex.RLock() + defer m.cacheMutex.RUnlock() + if nodeinfo, ok := m.cache[key]; ok { + return nodeinfo.payload, nil + } + return nodeinfoPayload{}, errors.New("No cache entry found") +} + +// Handles a nodeinfo request/response - called from the router +func (m *nodeinfo) handleNodeInfo(nodeinfo *nodeinfoReqRes) { + if nodeinfo.IsResponse { + m.callback(nodeinfo.SendPermPub, nodeinfo.NodeInfo) + m.addCachedNodeInfo(nodeinfo.SendPermPub, nodeinfo.NodeInfo) + } else { + m.sendNodeInfo(nodeinfo.SendPermPub, nodeinfo.SendCoords, true) + } +} + +// Send nodeinfo request or response - called from the router +func (m *nodeinfo) sendNodeInfo(key boxPubKey, coords []byte, isResponse bool) { + table := m.core.switchTable.table.Load().(lookupTable) + nodeinfo := nodeinfoReqRes{ + SendCoords: table.self.getCoords(), + IsResponse: isResponse, + NodeInfo: m.core.nodeinfo.getNodeInfo(), + } + bs := nodeinfo.encode() + shared := m.core.sessions.getSharedKey(&m.core.boxPriv, &key) + payload, nonce := boxSeal(shared, bs, nil) + p := wire_protoTrafficPacket{ + Coords: coords, + ToKey: key, + FromKey: m.core.boxPub, + Nonce: *nonce, + Payload: payload, + } + packet := p.encode() + m.core.router.out(packet) +} diff --git a/src/yggdrasil/router.go b/src/yggdrasil/router.go index 14e089f..1067067 100644 --- a/src/yggdrasil/router.go +++ b/src/yggdrasil/router.go @@ -409,10 +409,10 @@ func (r *router) handleProto(packet []byte) { r.handlePing(bs, &p.FromKey) case wire_SessionPong: r.handlePong(bs, &p.FromKey) - case wire_SessionMetaRequest: + case wire_NodeInfoRequest: fallthrough - case wire_SessionMetaResponse: - r.handleMetadata(bs, &p.FromKey) + case wire_NodeInfoResponse: + r.handleNodeInfo(bs, &p.FromKey) case wire_DHTLookupRequest: r.handleDHTReq(bs, &p.FromKey) case wire_DHTLookupResponse: @@ -457,14 +457,14 @@ func (r *router) handleDHTRes(bs []byte, fromKey *boxPubKey) { r.core.dht.handleRes(&res) } -// Decodes meta request -func (r *router) handleMetadata(bs []byte, fromKey *boxPubKey) { - req := sessionMeta{} +// Decodes nodeinfo request +func (r *router) handleNodeInfo(bs []byte, fromKey *boxPubKey) { + req := nodeinfoReqRes{} if !req.decode(bs) { return } req.SendPermPub = *fromKey - r.core.metadata.handleMetadata(&req) + r.core.nodeinfo.handleNodeInfo(&req) } // Passed a function to call. diff --git a/src/yggdrasil/session.go b/src/yggdrasil/session.go index dbd273f..4f2bedf 100644 --- a/src/yggdrasil/session.go +++ b/src/yggdrasil/session.go @@ -54,14 +54,6 @@ type sessionPing struct { MTU uint16 } -// Represents a session metadata packet. -type sessionMeta struct { - SendPermPub boxPubKey // Sender's permanent key - SendCoords []byte // Sender's coords - IsResponse bool - Metadata metadataPayload -} - // Updates session info in response to a ping, after checking that the ping is OK. // Returns true if the session was updated, or false otherwise. func (s *sessionInfo) update(p *sessionPing) bool { diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index d46994d..5e87784 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -16,8 +16,8 @@ const ( wire_SessionPong // inside protocol traffic header wire_DHTLookupRequest // inside protocol traffic header wire_DHTLookupResponse // inside protocol traffic header - wire_SessionMetaRequest // inside protocol traffic header - wire_SessionMetaResponse // inside protocol traffic header + wire_NodeInfoRequest // inside protocol traffic header + wire_NodeInfoResponse // inside protocol traffic header ) // Calls wire_put_uint64 on a nil slice. @@ -355,39 +355,39 @@ func (p *sessionPing) decode(bs []byte) bool { //////////////////////////////////////////////////////////////////////////////// -// Encodes a sessionMeta into its wire format. -func (p *sessionMeta) encode() []byte { +// Encodes a nodeinfoReqRes into its wire format. +func (p *nodeinfoReqRes) encode() []byte { var pTypeVal uint64 if p.IsResponse { - pTypeVal = wire_SessionMetaResponse + pTypeVal = wire_NodeInfoResponse } else { - pTypeVal = wire_SessionMetaRequest + pTypeVal = wire_NodeInfoRequest } bs := wire_encode_uint64(pTypeVal) bs = wire_put_coords(p.SendCoords, bs) - if pTypeVal == wire_SessionMetaResponse { - bs = append(bs, p.Metadata...) + if pTypeVal == wire_NodeInfoResponse { + bs = append(bs, p.NodeInfo...) } return bs } -// Decodes an encoded sessionMeta into the struct, returning true if successful. -func (p *sessionMeta) decode(bs []byte) bool { +// Decodes an encoded nodeinfoReqRes into the struct, returning true if successful. +func (p *nodeinfoReqRes) decode(bs []byte) bool { var pType uint64 switch { case !wire_chop_uint64(&pType, &bs): return false - case pType != wire_SessionMetaRequest && pType != wire_SessionMetaResponse: + case pType != wire_NodeInfoRequest && pType != wire_NodeInfoResponse: return false case !wire_chop_coords(&p.SendCoords, &bs): return false } - if p.IsResponse = pType == wire_SessionMetaResponse; p.IsResponse { + if p.IsResponse = pType == wire_NodeInfoResponse; p.IsResponse { if len(bs) == 0 { return false } - p.Metadata = make(metadataPayload, len(bs)) - if !wire_chop_slice(p.Metadata[:], &bs) { + p.NodeInfo = make(nodeinfoPayload, len(bs)) + if !wire_chop_slice(p.NodeInfo[:], &bs) { return false } }