-
Notifications
You must be signed in to change notification settings - Fork 2
/
listener.go
96 lines (76 loc) · 1.84 KB
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package p2p
import (
"errors"
"sync"
p2phost "github.com/libp2p/go-libp2p-core/host"
net "github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/protocol"
ma "github.com/multiformats/go-multiaddr"
)
// Listener listens for connections and proxies them to a target
type Listener interface {
Protocol() protocol.ID
ListenAddress() ma.Multiaddr
TargetAddress() ma.Multiaddr
key() string
// close closes the listener. Does not affect child streams
close()
}
// Listeners manages a group of Listener implementations,
// checking for conflicts and optionally dispatching connections
type Listeners struct {
sync.RWMutex
Listeners map[string]Listener
}
func newListenersLocal() *Listeners {
return &Listeners{
Listeners: map[string]Listener{},
}
}
func newListenersP2P(host p2phost.Host) *Listeners {
reg := &Listeners{
Listeners: map[string]Listener{},
}
host.SetStreamHandlerMatch("/x/", func(p string) bool {
reg.RLock()
defer reg.RUnlock()
_, ok := reg.Listeners[p]
return ok
}, func(stream net.Stream) {
reg.RLock()
defer reg.RUnlock()
l := reg.Listeners[string(stream.Protocol())]
if l != nil {
go l.(*remoteListener).handleStream(stream)
}
})
return reg
}
// Register registers listenerInfo into this registry and starts it
func (r *Listeners) Register(l Listener) error {
r.Lock()
defer r.Unlock()
if _, ok := r.Listeners[l.key()]; ok {
return errors.New("listener already registered")
}
r.Listeners[l.key()] = l
return nil
}
func (r *Listeners) Close(matchFunc func(listener Listener) bool) int {
todo := make([]Listener, 0)
r.Lock()
for _, l := range r.Listeners {
if !matchFunc(l) {
continue
}
if _, ok := r.Listeners[l.key()]; ok {
delete(r.Listeners, l.key())
todo = append(todo, l)
}
}
r.Unlock()
for _, l := range todo {
l.close()
}
return len(todo)
}