-
Notifications
You must be signed in to change notification settings - Fork 18
/
conn.go
323 lines (269 loc) · 7.53 KB
/
conn.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package peerstream
import (
"errors"
"fmt"
"net"
"sync"
smux "gx/ipfs/Qmb1US8uyZeEpMyc56wVZy2cDFdQjNFojAUYVCoo9ieTqp/go-stream-muxer"
)
// ConnHandler is a function which receives a Conn. It allows
// clients to set a function to receive newly accepted
// connections. It works like StreamHandler, but is usually
// less useful than usual as most services will only use
// Streams. It is safe to pass or store the *Conn elsewhere.
// Note: the ConnHandler is called sequentially, so spawn
// goroutines or pass the Conn. See EchoHandler.
type ConnHandler func(s *Conn)
// SelectConn selects a connection out of list. It allows
// delegation of decision making to clients. Clients can
// make SelectConn functons that check things connection
// qualities -- like latency andbandwidth -- or pick from
// a logical set of connections.
type SelectConn func([]*Conn) *Conn
// ErrInvalidConnSelected signals that a connection selected
// with a SelectConn function is invalid. This may be due to
// the Conn not being part of the original set given to the
// function, or the value being nil.
var ErrInvalidConnSelected = errors.New("invalid selected connection")
// ErrNoConnections signals that no connections are available
var ErrNoConnections = errors.New("no connections")
// Conn is a Swarm-associated connection.
type Conn struct {
smuxConn smux.Conn
netConn net.Conn // underlying connection
swarm *Swarm
groups groupSet
streams map[*Stream]struct{}
streamLock sync.RWMutex
closed bool
closeLock sync.Mutex
closing bool
closingLock sync.Mutex
}
func newConn(nconn net.Conn, tconn smux.Conn, s *Swarm) *Conn {
return &Conn{
netConn: nconn,
smuxConn: tconn,
swarm: s,
groups: groupSet{m: make(map[Group]struct{})},
streams: make(map[*Stream]struct{}),
}
}
// String returns a string representation of the Conn
func (c *Conn) String() string {
c.streamLock.RLock()
ls := len(c.streams)
c.streamLock.RUnlock()
f := "<peerstream.Conn %d streams %s <--> %s>"
return fmt.Sprintf(f, ls, c.netConn.LocalAddr(), c.netConn.RemoteAddr())
}
// Swarm returns the Swarm associated with this Conn
func (c *Conn) Swarm() *Swarm {
return c.swarm
}
// NetConn returns the underlying net.Conn
func (c *Conn) NetConn() net.Conn {
return c.netConn
}
// Conn returns the underlying transport Connection we use
// Warning: modifying this object is undefined.
func (c *Conn) Conn() smux.Conn {
return c.smuxConn
}
// Groups returns the Groups this Conn belongs to
func (c *Conn) Groups() []Group {
return c.groups.Groups()
}
// InGroup returns whether this Conn belongs to a Group
func (c *Conn) InGroup(g Group) bool {
return c.groups.Has(g)
}
// AddGroup assigns given Group to Conn
func (c *Conn) AddGroup(g Group) {
c.groups.Add(g)
}
// Stream returns a stream associated with this Conn
func (c *Conn) NewStream() (*Stream, error) {
return c.swarm.NewStreamWithConn(c)
}
func (c *Conn) Streams() []*Stream {
c.streamLock.RLock()
defer c.streamLock.RUnlock()
streams := make([]*Stream, 0, len(c.streams))
for s := range c.streams {
streams = append(streams, s)
}
return streams
}
// GoClose spawns off a goroutine to close the connection iff the connection is
// not already being closed and returns immediately
func (c *Conn) GoClose() {
c.closingLock.Lock()
defer c.closingLock.Unlock()
if c.closing {
return
}
c.closing = true
go c.Close()
}
// Close closes this connection
func (c *Conn) Close() error {
c.closeLock.Lock()
defer c.closeLock.Unlock()
if c.closed == true {
return nil
}
c.closingLock.Lock()
c.closing = true
c.closingLock.Unlock()
c.closed = true
// close streams
streams := c.Streams()
for _, s := range streams {
s.Close()
}
// close underlying connection
c.swarm.removeConn(c)
var err error
if c.smuxConn != nil {
err = c.smuxConn.Close()
} else {
err = c.netConn.Close()
}
c.swarm.notifyAll(func(n Notifiee) {
n.Disconnected(c)
})
return err
}
// ConnsWithGroup narrows down a set of connections to those in a given group.
func ConnsWithGroup(g Group, conns []*Conn) []*Conn {
var out []*Conn
for _, c := range conns {
if c.InGroup(g) {
out = append(out, c)
}
}
return out
}
func ConnInConns(c1 *Conn, conns []*Conn) bool {
for _, c2 := range conns {
if c2 == c1 {
return true
}
}
return false
}
// ------------------------------------------------------------------
// All the connection setup logic here, in one place.
// these are mostly *Swarm methods, but i wanted a less-crowded place
// for them.
// ------------------------------------------------------------------
// addConn is the internal version of AddConn. we need the server bool
// as spdystream requires it.
func (s *Swarm) addConn(netConn net.Conn, isServer bool) (*Conn, error) {
c, err := s.setupConn(netConn, isServer)
if err != nil {
return nil, err
}
s.ConnHandler()(c)
if c.smuxConn != nil {
// go listen for incoming streams on this connection
go c.smuxConn.Serve(func(ss smux.Stream) {
// log.Printf("accepted stream %d from %s\n", ssS.Identifier(), netConn.RemoteAddr())
stream := s.setupStream(ss, c)
s.StreamHandler()(stream) // call our handler
})
}
s.notifyAll(func(n Notifiee) {
n.Connected(c)
})
return c, nil
}
// setupConn adds the relevant connection to the map, first checking if it
// was already there.
func (s *Swarm) setupConn(netConn net.Conn, isServer bool) (*Conn, error) {
if netConn == nil {
return nil, errors.New("nil conn")
}
// first, check if we already have it, to avoid constructing it
// if it is already there
s.connLock.Lock()
for c := range s.conns {
if c.netConn == netConn {
s.connLock.Unlock()
return c, nil
}
}
s.connLock.Unlock()
// construct the connection without hanging onto the lock
// (as there could be deadlock if so.)
var ssConn smux.Conn
if s.transport != nil {
// create a new stream muxer connection
c, err := s.transport.NewConn(netConn, isServer)
if err != nil {
return nil, err
}
ssConn = c
}
// take the lock to add it to the map.
s.connLock.Lock()
defer s.connLock.Unlock()
// check for it again as it may have been added already. (TOCTTOU)
for c := range s.conns {
if c.netConn == netConn {
return c, nil
}
}
// add the connection
c := newConn(netConn, ssConn, s)
s.conns[c] = struct{}{}
return c, nil
}
// createStream is the internal function that creates a new stream. assumes
// all validation has happened.
func (s *Swarm) createStream(c *Conn) (*Stream, error) {
// Create a new smux.Stream
smuxStream, err := c.smuxConn.OpenStream()
if err != nil {
return nil, err
}
return s.setupStream(smuxStream, c), nil
}
// newStream is the internal function that creates a new stream. assumes
// all validation has happened.
func (s *Swarm) setupStream(smuxStream smux.Stream, c *Conn) *Stream {
// create a new stream
stream := newStream(smuxStream, c)
// add it to our streams maps
s.streamLock.Lock()
c.streamLock.Lock()
s.streams[stream] = struct{}{}
c.streams[stream] = struct{}{}
s.streamLock.Unlock()
c.streamLock.Unlock()
s.notifyAll(func(n Notifiee) {
n.OpenedStream(stream)
})
return stream
}
func (s *Swarm) removeStream(stream *Stream) error {
// remove from our maps
s.streamLock.Lock()
stream.conn.streamLock.Lock()
delete(s.streams, stream)
delete(stream.conn.streams, stream)
s.streamLock.Unlock()
stream.conn.streamLock.Unlock()
err := stream.smuxStream.Close()
s.notifyAll(func(n Notifiee) {
n.ClosedStream(stream)
})
return err
}
func (s *Swarm) removeConn(conn *Conn) {
// remove from our maps
s.connLock.Lock()
delete(s.conns, conn)
s.connLock.Unlock()
}