2019-01-19 00:42:53 +00:00
|
|
|
package yggdrasil
|
|
|
|
|
|
|
|
import (
|
2019-01-23 15:08:19 +00:00
|
|
|
"errors"
|
2019-01-19 00:42:53 +00:00
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type awdl struct {
|
|
|
|
core *Core
|
|
|
|
mutex sync.RWMutex // protects interfaces below
|
|
|
|
interfaces map[string]*awdlInterface
|
|
|
|
}
|
|
|
|
|
|
|
|
type awdlInterface struct {
|
2019-01-23 15:08:19 +00:00
|
|
|
link *linkInterface
|
|
|
|
rwc awdlReadWriteCloser
|
|
|
|
peer *peer
|
|
|
|
stream stream
|
|
|
|
}
|
|
|
|
|
|
|
|
type awdlReadWriteCloser struct {
|
2019-01-19 00:42:53 +00:00
|
|
|
fromAWDL chan []byte
|
|
|
|
toAWDL chan []byte
|
2019-01-23 15:08:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c awdlReadWriteCloser) Read(p []byte) (n int, err error) {
|
|
|
|
p = <-c.fromAWDL
|
|
|
|
return len(p), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c awdlReadWriteCloser) Write(p []byte) (n int, err error) {
|
|
|
|
c.toAWDL <- p
|
|
|
|
return len(p), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c awdlReadWriteCloser) Close() error {
|
|
|
|
close(c.fromAWDL)
|
|
|
|
close(c.toAWDL)
|
|
|
|
return nil
|
2019-01-19 00:42:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *awdl) init(c *Core) error {
|
|
|
|
l.core = c
|
|
|
|
l.mutex.Lock()
|
|
|
|
l.interfaces = make(map[string]*awdlInterface)
|
|
|
|
l.mutex.Unlock()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-01-23 15:08:19 +00:00
|
|
|
func (l *awdl) create(fromAWDL chan []byte, toAWDL chan []byte, name, local, remote string) (*awdlInterface, error) {
|
|
|
|
rwc := awdlReadWriteCloser{
|
|
|
|
fromAWDL: fromAWDL,
|
|
|
|
toAWDL: toAWDL,
|
|
|
|
}
|
|
|
|
s := stream{}
|
|
|
|
s.init(rwc, nil)
|
|
|
|
link, err := l.core.link.create(&s, name, "awdl", local, remote)
|
2019-01-19 00:42:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
intf := awdlInterface{
|
2019-01-23 15:08:19 +00:00
|
|
|
link: link,
|
|
|
|
rwc: rwc,
|
2019-01-19 22:37:45 +00:00
|
|
|
}
|
2019-01-23 15:08:19 +00:00
|
|
|
intf.stream.init(intf.rwc, nil)
|
2019-01-19 00:42:53 +00:00
|
|
|
l.mutex.Lock()
|
|
|
|
l.interfaces[name] = &intf
|
|
|
|
l.mutex.Unlock()
|
2019-01-23 15:08:19 +00:00
|
|
|
go link.handler()
|
2019-01-19 00:42:53 +00:00
|
|
|
return &intf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *awdl) getInterface(identity string) *awdlInterface {
|
|
|
|
l.mutex.RLock()
|
|
|
|
defer l.mutex.RUnlock()
|
|
|
|
if intf, ok := l.interfaces[identity]; ok {
|
|
|
|
return intf
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *awdl) shutdown(identity string) error {
|
|
|
|
if intf, ok := l.interfaces[identity]; ok {
|
2019-01-23 15:08:19 +00:00
|
|
|
close(intf.link.closed)
|
|
|
|
intf.rwc.Close()
|
2019-01-19 00:42:53 +00:00
|
|
|
l.mutex.Lock()
|
|
|
|
delete(l.interfaces, identity)
|
|
|
|
l.mutex.Unlock()
|
|
|
|
return nil
|
|
|
|
}
|
2019-01-23 15:08:19 +00:00
|
|
|
return errors.New("Interface not found or already closed")
|
2019-01-19 00:42:53 +00:00
|
|
|
}
|