yggdrasil-go/src/yggdrasil/awdl.go

99 lines
1.8 KiB
Go
Raw Normal View History

package yggdrasil
import (
2019-01-23 18:08:19 +03:00
"errors"
2019-01-23 20:05:16 +03:00
"io"
"sync"
)
type awdl struct {
core *Core
mutex sync.RWMutex // protects interfaces below
interfaces map[string]*awdlInterface
}
type awdlInterface struct {
2019-01-23 18:08:19 +03:00
link *linkInterface
rwc awdlReadWriteCloser
peer *peer
stream stream
}
type awdlReadWriteCloser struct {
fromAWDL chan []byte
toAWDL chan []byte
2019-01-23 18:08:19 +03:00
}
func (c awdlReadWriteCloser) Read(p []byte) (n int, err error) {
2019-01-23 20:05:16 +03:00
select {
case packet := <-c.fromAWDL:
n = copy(p, packet)
return n, nil
default:
return 0, io.EOF
}
2019-01-23 18:08:19 +03:00
}
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
}
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 20:05:16 +03:00
func (l *awdl) create(name, local, remote string) (*awdlInterface, error) {
2019-01-23 18:08:19 +03:00
rwc := awdlReadWriteCloser{
2019-01-23 20:05:16 +03:00
fromAWDL: make(chan []byte, 1),
toAWDL: make(chan []byte, 1),
2019-01-23 18:08:19 +03:00
}
s := stream{}
2019-01-23 18:16:22 +03:00
s.init(rwc)
2019-01-23 18:08:19 +03:00
link, err := l.core.link.create(&s, name, "awdl", local, remote)
if err != nil {
return nil, err
}
intf := awdlInterface{
2019-01-23 18:08:19 +03:00
link: link,
rwc: rwc,
}
l.mutex.Lock()
l.interfaces[name] = &intf
l.mutex.Unlock()
2019-01-23 20:05:16 +03:00
go intf.link.handler()
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 18:08:19 +03:00
close(intf.link.closed)
intf.rwc.Close()
l.mutex.Lock()
delete(l.interfaces, identity)
l.mutex.Unlock()
return nil
}
2019-01-23 18:08:19 +03:00
return errors.New("Interface not found or already closed")
}