-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
205 lines (168 loc) · 4.03 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
package remotedialer
import (
"context"
"errors"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
type session struct {
sync.Mutex
nextConnID int64
clientKey string
sessionKey int64
conn *wsConn
conns map[int64]*connection
auth ConnectAuthorizer
pingCancel context.CancelFunc
pingWait sync.WaitGroup
client bool
}
func newClientSession(auth ConnectAuthorizer, conn *websocket.Conn) *session {
return &session{
clientKey: "client",
conn: newWSConn(conn),
conns: map[int64]*connection{},
auth: auth,
client: true,
}
}
func newSession(sessionKey int64, clientKey string, conn *websocket.Conn) *session {
return &session{
nextConnID: 1,
clientKey: clientKey,
sessionKey: sessionKey,
conn: newWSConn(conn),
conns: map[int64]*connection{},
}
}
func (s *session) startPings() {
ctx, cancel := context.WithCancel(context.Background())
s.pingCancel = cancel
s.pingWait.Add(1)
go func() {
defer s.pingWait.Done()
t := time.NewTicker(PingWriteInterval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
s.conn.Lock()
if err := s.conn.conn.WriteControl(websocket.PingMessage, []byte(""), time.Now().Add(time.Second)); err != nil {
logrus.WithError(err).Error("Error writing ping")
}
logrus.Debug("Wrote ping")
s.conn.Unlock()
}
}
}()
}
func (s *session) stopPings() {
if s.pingCancel == nil {
return
}
s.pingCancel()
s.pingWait.Wait()
}
func (s *session) serve() (int, error) {
if s.client {
s.startPings()
}
for {
msType, reader, err := s.conn.NextReader()
if err != nil {
return 400, err
}
if msType != websocket.BinaryMessage {
return 400, errWrongMessageType
}
if err := s.serveMessage(reader); err != nil {
return 500, err
}
}
}
func (s *session) serveMessage(reader io.Reader) error {
message, err := newServerMessage(reader)
if err != nil {
return err
}
logrus.Debug("REQUEST ", message)
if message.messageType == Connect {
if s.auth == nil || !s.auth(message.proto, message.address) {
return errors.New("connect not allowed")
}
s.clientConnect(message)
return nil
}
s.Lock()
conn := s.conns[message.connID]
s.Unlock()
if conn == nil {
if message.messageType == Data {
err := fmt.Errorf("connection not found %s/%d/%d", s.clientKey, s.sessionKey, message.connID)
newErrorMessage(message.connID, err).WriteTo(s.conn)
}
return nil
}
switch message.messageType {
case Data:
if _, err := io.Copy(conn.tunnelWriter(), message); err != nil {
s.closeConnection(message.connID, err)
}
case Error:
s.closeConnection(message.connID, message.Err())
}
return nil
}
func (s *session) closeConnection(connID int64, err error) {
s.Lock()
conn := s.conns[connID]
delete(s.conns, connID)
logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns))
s.Unlock()
if conn != nil {
conn.tunnelClose(err)
}
}
func (s *session) clientConnect(message *message) {
conn := newConnection(message.connID, s, message.proto, message.address)
s.Lock()
s.conns[message.connID] = conn
logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns))
s.Unlock()
go clientDial(conn, message)
}
func (s *session) serverConnect(deadline time.Duration, proto, address string) (net.Conn, error) {
connID := atomic.AddInt64(&s.nextConnID, 1)
conn := newConnection(connID, s, proto, address)
s.Lock()
s.conns[connID] = conn
logrus.Debugf("CONNECTIONS %d %d", s.sessionKey, len(s.conns))
s.Unlock()
_, err := s.writeMessage(newConnect(connID, deadline, proto, address))
if err != nil {
s.closeConnection(connID, err)
return nil, err
}
return conn, err
}
func (s *session) writeMessage(message *message) (int, error) {
logrus.Debug("RESPONSE ", message)
return message.WriteTo(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{}
}