-
Notifications
You must be signed in to change notification settings - Fork 98
/
session.go
320 lines (267 loc) · 7.26 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
package remotedialer
import (
"context"
"errors"
"fmt"
"net"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
type Session struct {
sync.RWMutex
nextConnID int64
clientKey string
sessionKey int64
conn wsConn
conns map[int64]*connection
remoteClientKeys map[string]map[int]bool
auth ConnectAuthorizer
pingCancel context.CancelFunc
pingWait sync.WaitGroup
dialer Dialer
client bool
}
// PrintTunnelData No tunnel logging by default
var PrintTunnelData bool
func init() {
if os.Getenv("CATTLE_TUNNEL_DATA_DEBUG") == "true" {
PrintTunnelData = true
}
}
func NewClientSession(auth ConnectAuthorizer, conn *websocket.Conn) *Session {
return NewClientSessionWithDialer(auth, conn, nil)
}
func NewClientSessionWithDialer(auth ConnectAuthorizer, conn *websocket.Conn, dialer Dialer) *Session {
return &Session{
clientKey: "client",
conn: newWSConn(conn),
conns: map[int64]*connection{},
auth: auth,
client: true,
dialer: dialer,
}
}
func newSession(sessionKey int64, clientKey string, conn wsConn) *Session {
return &Session{
nextConnID: 1,
clientKey: clientKey,
sessionKey: sessionKey,
conn: conn,
conns: map[int64]*connection{},
remoteClientKeys: map[string]map[int]bool{},
}
}
// addConnection safely registers a new connection in the connections map
func (s *Session) addConnection(connID int64, conn *connection) {
s.Lock()
defer s.Unlock()
s.conns[connID] = conn
if PrintTunnelData {
logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns))
}
}
// removeConnection safely removes a connection by ID, returning the connection object
func (s *Session) removeConnection(connID int64) *connection {
s.Lock()
defer s.Unlock()
conn := s.removeConnectionLocked(connID)
if PrintTunnelData {
defer logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns))
}
return conn
}
// removeConnectionLocked removes a given connection from the session.
// The session lock must be held by the caller when calling this method
func (s *Session) removeConnectionLocked(connID int64) *connection {
conn := s.conns[connID]
delete(s.conns, connID)
return conn
}
// getConnection retrieves a connection by ID
func (s *Session) getConnection(connID int64) *connection {
s.RLock()
defer s.RUnlock()
return s.conns[connID]
}
// activeConnectionIDs returns an ordered list of IDs for the currently active connections
func (s *Session) activeConnectionIDs() []int64 {
s.RLock()
defer s.RUnlock()
res := make([]int64, 0, len(s.conns))
for id := range s.conns {
res = append(res, id)
}
sort.Slice(res, func(i, j int) bool { return res[i] < res[j] })
return res
}
// addSessionKey registers a new session key for a given client key
func (s *Session) addSessionKey(clientKey string, sessionKey int) {
s.Lock()
defer s.Unlock()
keys := s.remoteClientKeys[clientKey]
if keys == nil {
keys = map[int]bool{}
s.remoteClientKeys[clientKey] = keys
}
keys[sessionKey] = true
}
// removeSessionKey removes a specific session key for a client key
func (s *Session) removeSessionKey(clientKey string, sessionKey int) {
s.Lock()
defer s.Unlock()
keys := s.remoteClientKeys[clientKey]
delete(keys, sessionKey)
if len(keys) == 0 {
delete(s.remoteClientKeys, clientKey)
}
}
// getSessionKeys retrieves all session keys for a given client key
func (s *Session) getSessionKeys(clientKey string) map[int]bool {
s.RLock()
defer s.RUnlock()
return s.remoteClientKeys[clientKey]
}
func (s *Session) startPings(rootCtx context.Context) {
ctx, cancel := context.WithCancel(rootCtx)
s.pingCancel = cancel
s.pingWait.Add(1)
go func() {
defer s.pingWait.Done()
t := time.NewTicker(PingWriteInterval)
defer t.Stop()
syncConnections := time.NewTicker(SyncConnectionsInterval)
defer syncConnections.Stop()
for {
select {
case <-ctx.Done():
return
case <-syncConnections.C:
if err := s.sendSyncConnections(); err != nil {
logrus.WithError(err).Error("Error syncing connections")
}
case <-t.C:
if err := s.sendPing(); err != nil {
logrus.WithError(err).Error("Error writing ping")
}
logrus.Debug("Wrote ping")
}
}
}()
}
// sendPing sends a Ping control message to the peer
func (s *Session) sendPing() error {
return s.conn.WriteControl(websocket.PingMessage, time.Now().Add(PingWaitDuration), []byte(""))
}
func (s *Session) stopPings() {
if s.pingCancel == nil {
return
}
s.pingCancel()
s.pingWait.Wait()
}
func (s *Session) Serve(ctx context.Context) (int, error) {
if s.client {
s.startPings(ctx)
}
for {
msType, reader, err := s.conn.NextReader()
if err != nil {
return 400, err
}
if msType != websocket.BinaryMessage {
return 400, errWrongMessageType
}
if err := s.serveMessage(ctx, reader); err != nil {
return 500, err
}
}
}
func defaultDeadline() time.Time {
return time.Now().Add(time.Minute)
}
func parseAddress(address string) (string, int, error) {
parts := strings.SplitN(address, "/", 2)
if len(parts) != 2 {
return "", 0, errors.New("not / separated")
}
v, err := strconv.Atoi(parts[1])
return parts[0], v, err
}
type connResult struct {
conn net.Conn
err error
}
func (s *Session) Dial(ctx context.Context, proto, address string) (net.Conn, error) {
return s.serverConnectContext(ctx, proto, address)
}
func (s *Session) serverConnectContext(ctx context.Context, proto, address string) (net.Conn, error) {
deadline, ok := ctx.Deadline()
if ok {
return s.serverConnect(deadline, proto, address)
}
result := make(chan connResult, 1)
go func() {
c, err := s.serverConnect(defaultDeadline(), proto, address)
result <- connResult{conn: c, err: err}
}()
select {
case <-ctx.Done():
// We don't want to orphan an open connection so we wait for the result and immediately close it
go func() {
r := <-result
if r.err == nil {
r.conn.Close()
}
}()
return nil, ctx.Err()
case r := <-result:
return r.conn, r.err
}
}
func (s *Session) serverConnect(deadline time.Time, proto, address string) (net.Conn, error) {
connID := atomic.AddInt64(&s.nextConnID, 1)
conn := newConnection(connID, s, proto, address)
s.addConnection(connID, conn)
_, err := s.writeMessage(deadline, newConnect(connID, proto, address))
if err != nil {
s.closeConnection(connID, err)
return nil, err
}
return conn, err
}
func (s *Session) writeMessage(deadline time.Time, message *message) (int, error) {
if PrintTunnelData {
logrus.Debug("WRITE ", message)
}
return message.WriteTo(deadline, s.conn)
}
func (s *Session) Close() {
s.Lock()
defer s.Unlock()
s.stopPings()
for _, connection := range s.conns {
connection.tunnelClose(errors.New("tunnel disconnect"))
}
s.conns = map[int64]*connection{}
}
func (s *Session) sessionAdded(clientKey string, sessionKey int64) {
client := fmt.Sprintf("%s/%d", clientKey, sessionKey)
_, err := s.writeMessage(time.Time{}, newAddClient(client))
if err != nil {
s.conn.Close()
}
}
func (s *Session) sessionRemoved(clientKey string, sessionKey int64) {
client := fmt.Sprintf("%s/%d", clientKey, sessionKey)
_, err := s.writeMessage(time.Time{}, newRemoveClient(client))
if err != nil {
s.conn.Close()
}
}