-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
342 lines (289 loc) · 6.89 KB
/
session.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package wirenet
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/google/uuid"
"github.com/hashicorp/yamux"
)
// Session represents a connection between a client and a server.
// Each session can have from one to N named streams.
// Each named stream is a payload processing (file transfer, video transfer, etc.).
type Session interface {
// ID returns an unique session id.
ID() uuid.UUID
// IsClosed returns a true flag if the session is closed, otherwise returns a false flag.
IsClosed() bool
// Close closes gracefully shutdown the all active streams.
Close() error
// StreamNames returns a list of open stream names.
StreamNames() []string
// OpenStream opens a named stream and returns it.
// After the named stream is successfully opened, an authentication frame is sent.
OpenStream(name string) (Stream, error)
// Identification returns some information specified by the user on the client side using WithIdentification().
Identification() Identification
// CloseWire closes gracefully shutdown the server without interrupting any active connections.
CloseWire() error
}
type session struct {
id uuid.UUID
conn *yamux.Session
w *wire
streamNames []string
closed bool
closeCh chan chan error
activeStreams int
streams map[uuid.UUID]Stream
mu sync.RWMutex
timeoutDur time.Duration
identification Identification
}
func openSession(sid uuid.UUID, id Identification, conn *yamux.Session, w *wire, streamNames []string) {
sess := &session{
id: sid,
conn: conn,
w: w,
streamNames: streamNames,
closeCh: make(chan chan error),
streams: make(map[uuid.UUID]Stream),
timeoutDur: w.sessCloseTimeout,
identification: id,
}
go sess.open()
}
func (s *session) Identification() Identification {
s.mu.RLock()
defer s.mu.RUnlock()
return s.identification
}
func (s *session) StreamNames() []string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.streamNames
}
func (s *session) String() string {
return fmt.Sprintf("wirenet session: %s", s.id)
}
func (s *session) registerStream(stream Stream) {
s.mu.Lock()
defer s.mu.Unlock()
s.streams[stream.ID()] = stream
s.activeStreams++
}
func (s *session) unregisterStream(stream Stream) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.streams, stream.ID())
if s.activeStreams > 0 {
s.activeStreams--
}
}
func (s *session) activeStreamCounter() int {
s.mu.RLock()
defer s.mu.RUnlock()
return s.activeStreams
}
func (s *session) shutdown() context.Context {
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
errCh, ok := <-s.closeCh
if !ok {
return
}
timeout := time.Now().Add(s.timeoutDur)
for {
if s.activeStreamCounter() <= 0 {
break
}
if timeout.Unix() <= time.Now().Unix() {
for _, stream := range s.streams {
stream.Close()
}
continue
}
time.Sleep(300 * time.Millisecond)
}
cancel()
var closeErr error
if !s.conn.IsClosed() {
closeErr = s.conn.Close()
}
errCh <- closeErr
close(errCh)
break
}
}()
return ctx
}
func (s *session) validateStreamName(streamName string) (err error) {
isHubMode := s.w.isHubMode() && !s.w.role.IsClientSide()
if isHubMode {
_, err = s.w.findSession(streamName)
if err == ErrSessionNotFound {
_, err = s.w.findHandler(streamName)
}
} else {
_, err = s.w.findHandler(streamName)
}
return err
}
func (s *session) validateToken(streamName string, token []byte) (err error) {
if s.w.verifyToken != nil {
if err := s.w.verifyToken(streamName, s.identification, token); err != nil {
return err
}
}
return
}
func (s *session) readFrame(conn *yamux.Stream) (frm frame, err error) {
frm, err = recvFrame(conn, func(f frame) error {
command := f.Command()
if err := s.validateToken(command, f.Payload()); err != nil {
return err
}
return s.validateStreamName(command)
})
return frm, err
}
func (s *session) errLog(ctx context.Context, err error, op string) {
opErr := &OpError{
Op: op,
Err: err,
SessionID: s.id,
Identification: s.identification,
RemoteAddr: s.conn.RemoteAddr(),
LocalAddr: s.conn.LocalAddr(),
}
s.w.errorHandler(ctx, opErr)
}
func (s *session) dispatchStream(ctx context.Context, conn *yamux.Stream) {
defer func() {
_ = conn.Close()
}()
frm, err := s.readFrame(conn)
if err != nil {
s.errLog(ctx, err, "validate stream")
return
}
conn.Shrink()
streamName := frm.Command()
isHubMode := s.w.isHubMode() && !s.w.role.IsClientSide()
if isHubMode {
err = s.serveHub(ctx, streamName, conn)
if err == ErrSessionNotFound {
err = s.serve(ctx, streamName, conn)
}
} else {
err = s.serve(ctx, streamName, conn)
}
if err != nil {
s.errLog(ctx, err, "serve stream")
}
}
func (s *session) serveHub(_ context.Context, streamName string, conn *yamux.Stream) error {
sess, err := s.w.findSession(streamName)
if err != nil {
return err
}
dst, err := sess.OpenStream(streamName)
if err != nil {
return err
}
defer func() {
conn.Close()
dst.Close()
}()
dstConn := dst.(*stream).conn
go func() {
_ = pipe(dstConn, conn)
}()
return pipe(conn, dstConn)
}
func (s *session) serve(ctx context.Context, streamName string, conn *yamux.Stream) error {
defer func() {
if err := recover(); err != nil {
s.errLog(ctx, fmt.Errorf("recover %v", err), "recover stream")
}
}()
handler, err := s.w.findHandler(streamName)
if err != nil {
return err
}
stream := openStream(s, streamName, conn)
handler(ctx, stream)
if !stream.IsClosed() {
_ = stream.Close()
}
return nil
}
func (s *session) open() {
defer func() {
_ = s.Close()
}()
ctx := s.shutdown()
s.w.registerSession(s)
go s.w.openSessHook(s)
for {
conn, err := s.conn.AcceptStream()
if err != nil {
return
}
if s.IsClosed() || s.w.isClosed() {
_ = conn.Close()
continue
}
go s.dispatchStream(ctx, conn)
}
}
func (s *session) ID() uuid.UUID {
s.mu.RLock()
defer s.mu.RUnlock()
return s.id
}
func (s *session) IsClosed() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.closed
}
func (s *session) CloseWire() error {
return s.w.Close()
}
func (s *session) Close() error {
if s.IsClosed() {
return ErrSessionClosed
}
s.mu.Lock()
s.closed = true
s.mu.Unlock()
errCh := make(chan error)
s.closeCh <- errCh
closeErr := <-errCh
s.w.unregisterSession(s)
go s.w.closeSessHook(s)
return closeErr
}
func (s *session) OpenStream(name string) (Stream, error) {
if s.IsClosed() {
return nil, ErrSessionClosed
}
conn, err := s.conn.OpenStream()
if err != nil {
return nil, err
}
frm, err := sendFrame(name, permFrameTyp, s.w.token, conn)
if err != nil {
conn.Close()
return nil, err
}
if frm.Command() != name && !frm.IsRecvFrame() {
conn.Close()
return nil, io.ErrUnexpectedEOF
}
conn.Shrink()
stream := openStream(s, name, conn)
return stream, nil
}