yggdrasil-go/src/yggdrasil/awdl.go

112 lines
2.4 KiB
Go
Raw Normal View History

package yggdrasil
import (
2019-01-04 20:23:37 +03:00
"sync"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
)
type awdl struct {
2019-01-04 20:23:37 +03:00
core *Core
mutex sync.RWMutex // protects interfaces below
interfaces map[string]*awdlInterface
}
type awdlInterface struct {
2019-01-04 20:23:37 +03:00
awdl *awdl
recv <-chan []byte // traffic received from the network
send chan<- []byte // traffic to send to the network
shutdown chan bool
peer *peer
}
func (l *awdl) init(c *Core) error {
2019-01-04 20:23:37 +03:00
l.core = c
l.mutex.Lock()
l.interfaces = make(map[string]*awdlInterface)
l.mutex.Unlock()
2019-01-04 20:23:37 +03:00
return nil
}
func (l *awdl) create(boxPubKey *crypto.BoxPubKey, sigPubKey *crypto.SigPubKey, name string) *awdlInterface {
2019-01-04 20:23:37 +03:00
shared := crypto.GetSharedKey(&l.core.boxPriv, boxPubKey)
intf := awdlInterface{
recv: make(<-chan []byte),
send: make(chan<- []byte),
shutdown: make(chan bool),
peer: l.core.peers.newPeer(boxPubKey, sigPubKey, shared, name),
}
if intf.peer != nil {
l.mutex.Lock()
l.interfaces[name] = &intf
l.mutex.Unlock()
intf.peer.linkOut = make(chan []byte, 1)
intf.peer.out = func(msg []byte) {
defer func() { recover() }()
intf.send <- msg
2019-01-05 03:32:28 +03:00
l.core.switchTable.idleIn <- intf.peer.port
2019-01-04 20:23:37 +03:00
}
2019-01-05 03:52:41 +03:00
intf.peer.close = func() {
close(intf.send)
}
go intf.peer.linkLoop()
2019-01-04 20:23:37 +03:00
go intf.handler()
l.core.switchTable.idleIn <- intf.peer.port
return &intf
}
return nil
}
func (l *awdl) getInterface(identity string) *awdlInterface {
2019-01-04 20:23:37 +03:00
l.mutex.RLock()
defer l.mutex.RUnlock()
if intf, ok := l.interfaces[identity]; ok {
return intf
}
return nil
}
func (l *awdl) shutdown(identity string) {
2019-01-04 20:23:37 +03:00
if intf, ok := l.interfaces[identity]; ok {
intf.shutdown <- true
l.core.peers.removePeer(intf.peer.port)
l.mutex.Lock()
delete(l.interfaces, identity)
l.mutex.Unlock()
}
}
func (ai *awdlInterface) handler() {
2019-01-04 20:23:37 +03:00
for {
/*timerInterval := tcp_ping_interval
timer := time.NewTimer(timerInterval)
defer timer.Stop()*/
2019-01-04 20:23:37 +03:00
select {
case p := <-ai.peer.linkOut:
ai.send <- p
2019-01-05 03:32:28 +03:00
ai.awdl.core.switchTable.idleIn <- ai.peer.port
continue
default:
}
/*timer.Stop()
select {
case <-timer.C:
default:
}
timer.Reset(timerInterval)*/
select {
//case _ = <-timer.C:
// ai.send <- nil
2019-01-04 20:23:37 +03:00
case r := <-ai.recv: // traffic received from AWDL
ai.peer.handlePacket(r)
case <-ai.shutdown:
return
2019-01-05 04:02:22 +03:00
case p := <-ai.peer.linkOut:
ai.send <- p
ai.awdl.core.switchTable.idleIn <- ai.peer.port
continue
2019-01-04 20:23:37 +03:00
}
}
}