forked from wwt/guac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
239 lines (199 loc) · 6.28 KB
/
server.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
package guac
import (
"fmt"
logger "github.com/sirupsen/logrus"
"io"
"net/http"
"strings"
)
const (
readPrefix string = "read:"
writePrefix string = "write:"
readPrefixLength = len(readPrefix)
writePrefixLength = len(writePrefix)
uuidLength = 36
)
// Server uses HTTP requests to talk to guacd (as opposed to WebSockets in ws_server.go)
type Server struct {
tunnels *TunnelMap
connect func(*http.Request) (Tunnel, error)
}
// NewServer constructor
func NewServer(connect func(r *http.Request) (Tunnel, error)) *Server {
return &Server{
tunnels: NewTunnelMap(),
connect: connect,
}
}
// Registers the given tunnel such that future read/write requests to that tunnel will be properly directed.
func (s *Server) registerTunnel(tunnel Tunnel) {
s.tunnels.Put(tunnel.GetUUID(), tunnel)
logger.Debugf("Registered tunnel %v.", tunnel.GetUUID())
}
// Deregisters the given tunnel such that future read/write requests to that tunnel will be rejected.
func (s *Server) deregisterTunnel(tunnel Tunnel) {
s.tunnels.Remove(tunnel.GetUUID())
logger.Debugf("Deregistered tunnel %v.", tunnel.GetUUID())
}
// Returns the tunnel with the given UUID.
func (s *Server) getTunnel(tunnelUUID string) (ret Tunnel, err error) {
var ok bool
ret, ok = s.tunnels.Get(tunnelUUID)
if !ok {
err = ErrResourceNotFound.NewError("No such tunnel.")
}
return
}
func (s *Server) sendError(response http.ResponseWriter, guacStatus Status, message string) {
response.Header().Set("Guacamole-Status-Code", fmt.Sprintf("%v", guacStatus.GetGuacamoleStatusCode()))
response.Header().Set("Guacamole-Error-Message", message)
response.WriteHeader(guacStatus.GetHTTPStatusCode())
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := s.handleTunnelRequestCore(w, r)
if err == nil {
return
}
guacErr := err.(*ErrGuac)
switch guacErr.Kind {
case ErrClient:
logger.Warn("HTTP tunnel request rejected: ", err.Error())
s.sendError(w, guacErr.Status, err.Error())
default:
logger.Error("HTTP tunnel request failed: ", err.Error())
logger.Debug("Internal error in HTTP tunnel.", err)
s.sendError(w, guacErr.Status, "Internal server error.")
}
return
}
func (s *Server) handleTunnelRequestCore(response http.ResponseWriter, request *http.Request) (err error) {
query := request.URL.RawQuery
if len(query) == 0 {
return ErrClient.NewError("No query string provided.")
}
// Call the supplied connect callback upon HTTP connect request
if query == "connect" {
tunnel, e := s.connect(request)
if e != nil {
err = ErrResourceNotFound.NewError("No tunnel created.", e.Error())
return
}
s.registerTunnel(tunnel)
// Ensure buggy browsers do not cache response
response.Header().Set("Cache-Control", "no-cache")
_, e = response.Write([]byte(tunnel.GetUUID()))
if e != nil {
err = ErrServer.NewError(e.Error())
return
}
return
}
// Connect has already been called so we use the UUID to do read and writes to the existing session
if strings.HasPrefix(query, readPrefix) && len(query) >= readPrefixLength+uuidLength {
err = s.doRead(response, request, query[readPrefixLength:readPrefixLength+uuidLength])
} else if strings.HasPrefix(query, writePrefix) && len(query) >= writePrefixLength+uuidLength {
err = s.doWrite(response, request, query[writePrefixLength:writePrefixLength+uuidLength])
} else {
err = ErrClient.NewError("Invalid tunnel operation: " + query)
}
return
}
// doRead takes guacd messages and sends them in the response
func (s *Server) doRead(response http.ResponseWriter, request *http.Request, tunnelUUID string) error {
tunnel, err := s.getTunnel(tunnelUUID)
if err != nil {
return err
}
reader := tunnel.AcquireReader()
defer tunnel.ReleaseReader()
// Note that although we are sending text, Webkit browsers will
// buffer 1024 bytes before starting a normal stream if we use
// anything but application/octet-stream.
response.Header().Set("Content-Type", "application/octet-stream")
response.Header().Set("Cache-Control", "no-cache")
if v, ok := response.(http.Flusher); ok {
v.Flush()
}
err = s.writeSome(response, reader, tunnel)
if err == nil {
// success
return err
}
switch err.(*ErrGuac).Kind {
// Send end-of-stream marker and close tunnel if connection is closed
case ErrConnectionClosed:
s.deregisterTunnel(tunnel)
tunnel.Close()
// End-of-instructions marker
_, _ = response.Write([]byte("0.;"))
if v, ok := response.(http.Flusher); ok {
v.Flush()
}
default:
logger.Debugln("Error writing to output", err)
s.deregisterTunnel(tunnel)
tunnel.Close()
}
return err
}
// writeSome drains the guacd buffer holding instructions into the response
func (s *Server) writeSome(response http.ResponseWriter, guacd InstructionReader, tunnel Tunnel) (err error) {
var message []byte
for {
message, err = guacd.ReadSome()
if err != nil {
s.deregisterTunnel(tunnel)
tunnel.Close()
return
}
if len(message) == 0 {
return
}
_, e := response.Write(message)
if e != nil {
err = ErrOther.NewError(e.Error())
return
}
if !guacd.Available() {
if v, ok := response.(http.Flusher); ok {
v.Flush()
}
}
// No more messages another guacd can take over
if tunnel.HasQueuedReaderThreads() {
break
}
}
// End-of-instructions marker
if _, err = response.Write([]byte("0.;")); err != nil {
return err
}
if v, ok := response.(http.Flusher); ok {
v.Flush()
}
return nil
}
// doWrite takes data from the request and sends it to guacd
func (s *Server) doWrite(response http.ResponseWriter, request *http.Request, tunnelUUID string) error {
tunnel, err := s.getTunnel(tunnelUUID)
if err != nil {
return err
}
// We still need to set the content type to avoid the default of
// text/html, as such a content type would cause some browsers to
// attempt to parse the result, even though the JavaScript client
// does not explicitly request such parsing.
response.Header().Set("Content-Type", "application/octet-stream")
response.Header().Set("Cache-Control", "no-cache")
response.Header().Set("Content-Length", "0")
writer := tunnel.AcquireWriter()
defer tunnel.ReleaseWriter()
_, err = io.Copy(writer, request.Body)
if err != nil {
s.deregisterTunnel(tunnel)
if err = tunnel.Close(); err != nil {
logger.Debug("Error closing tunnel")
}
}
return err
}