-
Notifications
You must be signed in to change notification settings - Fork 29
/
websocket.go
388 lines (339 loc) · 9.61 KB
/
websocket.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package onet
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"go.dedis.ch/onet/v3/log"
"go.dedis.ch/onet/v3/network"
"golang.org/x/xerrors"
)
const certificateReloaderLeeway = 1 * time.Hour
// CertificateReloader takes care of reloading a TLS certificate when
// requested.
type CertificateReloader struct {
sync.RWMutex
cert *tls.Certificate
certPath string
keyPath string
}
// NewCertificateReloader takes two file paths as parameter that contain
// the certificate and the key data to create an automatic reloader. It will
// try to read again the files when the certificate is almost expired.
func NewCertificateReloader(certPath, keyPath string) (*CertificateReloader, error) {
loader := &CertificateReloader{
certPath: certPath,
keyPath: keyPath,
}
err := loader.reload()
if err != nil {
return nil, xerrors.Errorf("reloading certificate: %v", err)
}
return loader, nil
}
func (cr *CertificateReloader) reload() error {
newCert, err := tls.LoadX509KeyPair(cr.certPath, cr.keyPath)
if err != nil {
return xerrors.Errorf("load x509: %v", err)
}
cr.Lock()
cr.cert = &newCert
// Successful parse means at least one certificate.
cr.cert.Leaf, err = x509.ParseCertificate(newCert.Certificate[0])
cr.Unlock()
if err != nil {
return xerrors.Errorf("parse x509: %v", err)
}
return nil
}
// GetCertificateFunc makes a function that can be passed to the TLSConfig
// so that it resolves the most up-to-date one.
func (cr *CertificateReloader) GetCertificateFunc() func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
cr.RLock()
exp := time.Now().Add(certificateReloaderLeeway)
// Here we know the leaf has been parsed successfully as an error
// would have been thrown otherwise.
if cr.cert == nil || exp.After(cr.cert.Leaf.NotAfter) {
// Certificate has expired so we try to load the new one.
// Free the read lock to be able to reload.
cr.RUnlock()
err := cr.reload()
if err != nil {
return nil, xerrors.Errorf("reload certificate: %v", err)
}
cr.RLock()
}
defer cr.RUnlock()
return cr.cert, nil
}
}
// WebSocket handles incoming client-requests using the websocket
// protocol. When making a new WebSocket, it will listen one port above the
// ServerIdentity-port-#.
// The websocket protocol has been chosen as smallest common denominator
// for languages including JavaScript.
type WebSocket struct {
services map[string]Service
server *http.Server
mux *http.ServeMux
startstop chan bool
started bool
TLSConfig *tls.Config // can only be modified before Start is called
sync.Mutex
}
// NewWebSocket opens a webservice-listener at the given si.URL.
func NewWebSocket(si *network.ServerIdentity) *WebSocket {
w := &WebSocket{
services: make(map[string]Service),
startstop: make(chan bool),
}
webHost, err := getWSHostPort(si, true)
log.ErrFatal(err)
w.mux = http.NewServeMux()
w.mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {
log.Lvl4("ok?", r.RemoteAddr)
ok := []byte("ok\n")
w.Write(ok)
})
if allowPprof() {
log.Warn("HTTP pprof profiling is enabled")
initPprof(w.mux)
}
// Add a catch-all handler (longest paths take precedence, so "/" takes
// all non-registered paths) and correctly upgrade to a websocket and
// throw an error.
w.mux.HandleFunc("/", func(wr http.ResponseWriter, re *http.Request) {
log.Error("request from ", re.RemoteAddr, "for invalid path ", re.URL.Path)
u := websocket.Upgrader{
// The mobile app on iOS doesn't support compression well...
EnableCompression: false,
// As the website will not be served from ourselves, we
// need to accept _all_ origins. Cross-site scripting is
// required.
CheckOrigin: func(*http.Request) bool {
return true
},
}
ws, err := u.Upgrade(wr, re, http.Header{})
if err != nil {
log.Error(err)
return
}
ws.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(4001, "This service doesn't exist"),
time.Now().Add(time.Millisecond*500))
ws.Close()
})
w.server = &http.Server{
Addr: webHost,
Handler: w.mux,
}
return w
}
// Listening returns true if the server has been started and is
// listening on the ports for incoming connections.
func (w *WebSocket) Listening() bool {
w.Lock()
defer w.Unlock()
return w.started
}
// start listening on the port.
func (w *WebSocket) start() {
w.Lock()
w.started = true
w.server.TLSConfig = w.TLSConfig
log.Lvl2("Starting to listen on", w.server.Addr)
started := make(chan bool)
go func() {
// Check if server is configured for TLS
started <- true
if w.server.TLSConfig != nil && (w.server.TLSConfig.GetCertificate != nil || len(w.server.TLSConfig.Certificates) >= 1) {
w.server.ListenAndServeTLS("", "")
} else {
w.server.ListenAndServe()
}
}()
<-started
w.Unlock()
w.startstop <- true
}
// registerService stores a service to the given path. All requests to that
// path and it's sub-endpoints will be forwarded to ProcessClientRequest.
func (w *WebSocket) registerService(service string, s Service) error {
if service == "ok" {
return xerrors.New("service name \"ok\" is not allowed")
}
w.services[service] = s
h := &wsHandler{
service: s,
serviceName: service,
}
w.mux.Handle(fmt.Sprintf("/%s/", service), h)
return nil
}
// stop the websocket and free the port.
func (w *WebSocket) stop() {
w.Lock()
defer w.Unlock()
if !w.started {
return
}
log.Lvl3("Stopping", w.server.Addr)
d := time.Now().Add(100 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d)
w.server.Shutdown(ctx)
cancel()
<-w.startstop
w.started = false
}
// Pass the request to the websocket.
type wsHandler struct {
serviceName string
service Service
}
// Wrapper-function so that http.Requests get 'upgraded' to websockets
// and handled correctly.
func (t wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rx := 0
tx := 0
n := 0
defer func() {
log.Lvl2("ws close", r.RemoteAddr, "n", n, "rx", rx, "tx", tx)
}()
u := websocket.Upgrader{
// The mobile app on iOS doesn't support compression well...
EnableCompression: false,
// As the website will not be served from ourselves, we
// need to accept _all_ origins. Cross-site scripting is
// required.
CheckOrigin: func(*http.Request) bool {
return true
},
}
ws, err := u.Upgrade(w, r, http.Header{})
if err != nil {
log.Error(err)
return
}
defer ws.Close()
// Loop for each message
outerReadLoop:
for err == nil {
mt, buf, rerr := ws.ReadMessage()
if rerr != nil {
err = rerr
break
}
rx += len(buf)
n++
s := t.service
var reply []byte
var outChan chan []byte
path := strings.TrimPrefix(r.URL.Path, "/"+t.serviceName+"/")
log.Lvlf2("ws request from %s: %s/%s", r.RemoteAddr, t.serviceName, path)
isStreaming := false
bidirectionalStreamer, ok := s.(BidirectionalStreamer)
if ok {
isStreaming, err = bidirectionalStreamer.IsStreaming(path)
if err != nil {
log.Errorf("failed to check if it is a streaming "+
"request %s/%s: %+v", t.serviceName, path, err)
continue
}
}
if !isStreaming {
reply, _, err = s.ProcessClientRequest(r, path, buf)
if err != nil {
log.Errorf("Got an error while executing %s/%s: %+v",
t.serviceName, path, err)
continue
}
tx += len(reply)
err = ws.SetWriteDeadline(time.Now().Add(5 * time.Minute))
if err != nil {
log.Error(xerrors.Errorf("failed to set the write deadline "+
"with request request %s/%s: %v", t.serviceName, path, err))
break
}
err = ws.WriteMessage(mt, reply)
if err != nil {
log.Error(xerrors.Errorf("failed to write message with "+
"request %s/%s: %v", t.serviceName, path, err))
break
}
continue
}
clientInputs := make(chan []byte, 10)
clientInputs <- buf
outChan, err = bidirectionalStreamer.ProcessClientStreamRequest(r,
path, clientInputs)
if err != nil {
log.Errorf("got an error while processing streaming "+
"request %s/%s: %+v", t.serviceName, path, err)
continue
}
closing := make(chan bool)
go func() {
for {
// Listen for incoming messages to know if the client wants to
// close the stream. If this is an error, we assume the client
// wants to close the stream, otherwise we forward the message
// to the service.
_, buf, err := ws.ReadMessage()
if err != nil {
close(closing)
return
}
clientInputs <- buf
}
}()
for {
select {
case <-closing:
close(clientInputs)
break outerReadLoop
case reply, ok := <-outChan:
if !ok {
ws.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "service finished streaming"),
time.Now().Add(time.Millisecond*500))
close(clientInputs)
return
}
tx += len(reply)
err = ws.SetWriteDeadline(time.Now().Add(5 * time.Minute))
if err != nil {
log.Error(xerrors.Errorf("failed to set the write "+
"deadline in the streaming loop: %v", err))
close(clientInputs)
break outerReadLoop
}
err = ws.WriteMessage(mt, reply)
if err != nil {
log.Error(xerrors.Errorf("failed to write next message "+
"in the streaming loop: %v", err))
close(clientInputs)
break outerReadLoop
}
}
}
}
errMessage := "unexpected error: "
if err != nil {
errMessage += err.Error()
}
ws.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseProtocolError, errMessage),
time.Now().Add(time.Millisecond*500))
return
}
type destination struct {
si *network.ServerIdentity
path string
}