-
Notifications
You must be signed in to change notification settings - Fork 10
/
session.go
189 lines (166 loc) · 4.32 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
package bring
import (
"errors"
_ "golang.org/x/image/webp"
_ "image/jpeg"
_ "image/png"
"strings"
"time"
"github.com/deluan/bring/protocol"
)
type SessionState int
const (
SessionClosed SessionState = iota
SessionHandshake
SessionActive
)
const (
defaultWidth = "1024"
defaultHeight = "768"
)
var ErrNotConnected = errors.New("not connected")
const pingFrequency = 5 * time.Second
// Session is used to create and keep a connection with a guacd server,
// and it is responsible for the initial handshake and to send and receive instructions.
// Instructions received are put in the In channel. Instructions are sent using the Send() function
type session struct {
In chan *protocol.Instruction
State SessionState
Id string
tunnel protocol.Tunnel
logger Logger
done chan bool
config map[string]string
protocol string
}
// newSession creates a new connection with the guacd server, using the configuration provided
func newSession(addr string, remoteProtocol string, config map[string]string, logger Logger) (*session, error) {
t, err := protocol.NewInetSocketTunnel(addr)
if err != nil {
return nil, err
}
err = t.Connect("")
if err != nil {
logger.Errorf("Error connecting to '%s': %s", addr, err)
return nil, err
}
s := &session{
In: make(chan *protocol.Instruction, 100),
State: SessionClosed,
done: make(chan bool),
logger: logger,
tunnel: t,
config: config,
protocol: remoteProtocol,
}
s.logger.Infof("Initiating %s session with %s", strings.ToUpper(remoteProtocol), addr)
err = s.Send(protocol.NewInstruction("select", remoteProtocol))
if err != nil {
s.logger.Errorf("Failed sending 'select': %s", err)
return nil, err
}
s.State = SessionHandshake
s.startReader()
return s, nil
}
// Terminate the current session, disconnecting from the server
func (s *session) Terminate() {
if s.State == SessionClosed {
return
}
close(s.done)
s.State = SessionClosed
_ = s.tunnel.SendInstruction(protocol.NewInstruction("disconnect"))
s.tunnel.Disconnect()
}
// Send instructions to the server. Multiple instructions are sent in one single transaction
func (s *session) Send(ins ...*protocol.Instruction) error {
for _, i := range ins {
s.logger.Debugf("C> %s", i)
}
return s.tunnel.SendInstruction(ins...)
}
func (s *session) startKeepAlive() {
go func() {
ping := time.NewTicker(pingFrequency)
defer ping.Stop()
for {
select {
case <-ping.C:
err := s.Send(protocol.NewInstruction("nop"))
if err != nil {
s.logger.Errorf("Failed ping the server: %s", err)
}
case <-s.done:
return
}
}
}()
}
func (s *session) startReader() {
go func() {
for {
ins, err := s.tunnel.ReceiveInstruction()
if err != nil {
s.logger.Warnf("Disconnecting from server. Reason: " + err.Error())
s.Terminate()
break
}
if ins.Opcode == "blob" {
s.logger.Debugf("S> 4.blob: %d", len(ins.Args[1]))
} else {
s.logger.Debugf("S> %s", ins)
}
if ins.Opcode == "nop" {
continue
}
if ins.Opcode == "ready" {
s.State = SessionActive
s.Id = ins.Args[0]
s.logger.Infof("Handshake successful. Got connection ID %s", s.Id)
s.startKeepAlive()
continue
}
if s.State == SessionHandshake {
s.logger.Infof("Handshake started at %s", time.Now().Format(time.RFC3339))
s.handShake(ins)
continue
}
if s.State == SessionActive {
s.In <- ins
continue
}
s.logger.Warnf("Received out of order instruction: %s", ins)
}
}()
}
func (s *session) handShake(argsIns *protocol.Instruction) {
width := s.config["width"]
if width == "" {
width = defaultWidth
}
height := s.config["height"]
if height == "" {
height = defaultHeight
}
options := []*protocol.Instruction{
protocol.NewInstruction("size", width, height, "96"),
protocol.NewInstruction("audio"),
protocol.NewInstruction("video"),
protocol.NewInstruction("image", "image/png", "image/jpeg", "image/webp"),
}
err := s.Send(options...)
if err != nil {
s.logger.Errorf("Failed handshake: %s", err)
s.Terminate()
}
connectValues := make([]string, len(argsIns.Args))
for i, argName := range argsIns.Args {
connectValues[i] = s.config[argName]
}
err = s.Send(protocol.NewInstruction("connect", connectValues...))
if err != nil {
s.logger.Errorf("Failed handshake when sending 'connect': %s", err)
s.Terminate()
}
}