yggdrasil-go/src/yggdrasil/awdl.go

108 lines
2.0 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 {
link *link
reconfigure chan chan error
mutex sync.RWMutex // protects interfaces below
interfaces map[string]*awdlInterface
}
type awdlInterface struct {
2019-01-23 22:42:33 +03:00
linkif *linkInterface
2019-01-23 18:08:19 +03:00
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 21:16:31 +03:00
if packet, ok := <-c.fromAWDL; ok {
2019-01-23 20:05:16 +03:00
n = copy(p, packet)
return n, nil
}
2019-01-23 21:16:31 +03:00
return 0, io.EOF
2019-01-23 18:08:19 +03:00
}
func (c awdlReadWriteCloser) Write(p []byte) (n int, err error) {
2019-01-23 21:16:31 +03:00
var pc []byte
pc = append(pc, p...)
c.toAWDL <- pc
return len(pc), nil
2019-01-23 18:08:19 +03:00
}
func (c awdlReadWriteCloser) Close() error {
close(c.fromAWDL)
close(c.toAWDL)
return nil
}
2019-01-23 22:42:33 +03:00
func (a *awdl) init(l *link) error {
a.link = l
a.mutex.Lock()
a.interfaces = make(map[string]*awdlInterface)
a.reconfigure = make(chan chan error, 1)
2019-01-23 22:42:33 +03:00
a.mutex.Unlock()
go func() {
for {
e := <-a.reconfigure
e <- nil
}
}()
return nil
}
func (a *awdl) create(name, local, remote string, incoming bool) (*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)
linkif, err := a.link.create(&s, name, "awdl", local, remote, incoming, true)
if err != nil {
return nil, err
}
intf := awdlInterface{
2019-01-23 22:42:33 +03:00
linkif: linkif,
rwc: rwc,
}
2019-01-23 22:42:33 +03:00
a.mutex.Lock()
a.interfaces[name] = &intf
a.mutex.Unlock()
go intf.linkif.handler()
return &intf, nil
}
2019-01-23 22:42:33 +03:00
func (a *awdl) getInterface(identity string) *awdlInterface {
a.mutex.RLock()
defer a.mutex.RUnlock()
if intf, ok := a.interfaces[identity]; ok {
return intf
}
return nil
}
2019-01-23 22:42:33 +03:00
func (a *awdl) shutdown(identity string) error {
if intf, ok := a.interfaces[identity]; ok {
close(intf.linkif.closed)
2019-01-23 18:08:19 +03:00
intf.rwc.Close()
2019-01-23 22:42:33 +03:00
a.mutex.Lock()
delete(a.interfaces, identity)
a.mutex.Unlock()
return nil
}
2019-01-23 18:08:19 +03:00
return errors.New("Interface not found or already closed")
}