| 1 |
package centrifuge |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"net/http" |
| 6 |
"net/url" |
| 7 |
"strings" |
| 8 |
"sync" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/centrifugal/centrifuge/internal/cancelctx" |
| 12 |
"github.com/centrifugal/centrifuge/internal/timers" |
| 13 |
|
| 14 |
"github.com/gorilla/websocket" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
transportWebsocket = "websocket" |
| 19 |
) |
| 20 |
|
| 21 |
// websocketTransport is a wrapper struct over websocket connection to fit session |
| 22 |
// interface so client will accept it. |
| 23 |
type websocketTransport struct { |
| 24 |
mu sync.RWMutex |
| 25 |
conn *websocket.Conn |
| 26 |
closed bool |
| 27 |
closeCh chan struct{} |
| 28 |
graceCh chan struct{} |
| 29 |
opts websocketTransportOptions |
| 30 |
pingTimer *time.Timer |
| 31 |
} |
| 32 |
|
| 33 |
type websocketTransportOptions struct { |
| 34 |
encType EncodingType |
| 35 |
protoType ProtocolType |
| 36 |
pingInterval time.Duration |
| 37 |
writeTimeout time.Duration |
| 38 |
compressionMinSize int |
| 39 |
} |
| 40 |
|
| 41 |
func newWebsocketTransport(conn *websocket.Conn, opts websocketTransportOptions, graceCh chan struct{}) *websocketTransport { |
| 42 |
transport := &websocketTransport{ |
| 43 |
conn: conn, |
| 44 |
closeCh: make(chan struct{}), |
| 45 |
graceCh: graceCh, |
| 46 |
opts: opts, |
| 47 |
} |
| 48 |
if opts.pingInterval > 0 { |
| 49 |
transport.addPing() |
| 50 |
} |
| 51 |
return transport |
| 52 |
} |
| 53 |
|
| 54 |
func (t *websocketTransport) ping() { |
| 55 |
select { |
| 56 |
case <-t.closeCh: |
| 57 |
return |
| 58 |
default: |
| 59 |
deadline := time.Now().Add(t.opts.pingInterval / 2) |
| 60 |
err := t.conn.WriteControl(websocket.PingMessage, []byte("ping"), deadline) |
| 61 |
if err != nil { |
| 62 |
_ = t.Close(DisconnectServerError) |
| 63 |
return |
| 64 |
} |
| 65 |
t.addPing() |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
func (t *websocketTransport) addPing() { |
| 70 |
t.mu.Lock() |
| 71 |
if t.closed { |
| 72 |
t.mu.Unlock() |
| 73 |
return |
| 74 |
} |
| 75 |
t.pingTimer = time.AfterFunc(t.opts.pingInterval, t.ping) |
| 76 |
t.mu.Unlock() |
| 77 |
} |
| 78 |
|
| 79 |
// Name returns name of transport. |
| 80 |
func (t *websocketTransport) Name() string { |
| 81 |
return transportWebsocket |
| 82 |
} |
| 83 |
|
| 84 |
// Protocol returns transport protocol. |
| 85 |
func (t *websocketTransport) Protocol() ProtocolType { |
| 86 |
return t.opts.protoType |
| 87 |
} |
| 88 |
|
| 89 |
// Encoding returns transport encoding. |
| 90 |
func (t *websocketTransport) Encoding() EncodingType { |
| 91 |
return t.opts.encType |
| 92 |
} |
| 93 |
|
| 94 |
// Write data to transport. |
| 95 |
func (t *websocketTransport) Write(data []byte) error { |
| 96 |
select { |
| 97 |
case <-t.closeCh: |
| 98 |
return nil |
| 99 |
default: |
| 100 |
if t.opts.compressionMinSize > 0 { |
| 101 |
t.conn.EnableWriteCompression(len(data) > t.opts.compressionMinSize) |
| 102 |
} |
| 103 |
if t.opts.writeTimeout > 0 { |
| 104 |
_ = t.conn.SetWriteDeadline(time.Now().Add(t.opts.writeTimeout)) |
| 105 |
} |
| 106 |
|
| 107 |
var messageType = websocket.TextMessage |
| 108 |
if t.Protocol() == ProtocolTypeProtobuf { |
| 109 |
messageType = websocket.BinaryMessage |
| 110 |
} |
| 111 |
|
| 112 |
err := t.conn.WriteMessage(messageType, data) |
| 113 |
if err != nil { |
| 114 |
return err |
| 115 |
} |
| 116 |
|
| 117 |
if t.opts.writeTimeout > 0 { |
| 118 |
_ = t.conn.SetWriteDeadline(time.Time{}) |
| 119 |
} |
| 120 |
return nil |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
const closeFrameWait = 5 * time.Second |
| 125 |
|
| 126 |
// Close closes transport. |
| 127 |
func (t *websocketTransport) Close(disconnect *Disconnect) error { |
| 128 |
t.mu.Lock() |
| 129 |
if t.closed { |
| 130 |
t.mu.Unlock() |
| 131 |
return nil |
| 132 |
} |
| 133 |
t.closed = true |
| 134 |
if t.pingTimer != nil { |
| 135 |
t.pingTimer.Stop() |
| 136 |
} |
| 137 |
close(t.closeCh) |
| 138 |
t.mu.Unlock() |
| 139 |
|
| 140 |
if disconnect != nil { |
| 141 |
msg := websocket.FormatCloseMessage(int(disconnect.Code), disconnect.CloseText()) |
| 142 |
err := t.conn.WriteControl(websocket.CloseMessage, msg, time.Now().Add(time.Second)) |
| 143 |
if err != nil { |
| 144 |
return t.conn.Close() |
| 145 |
} |
| 146 |
select { |
| 147 |
case <-t.graceCh: |
| 148 |
default: |
| 149 |
// Wait for closing handshake completion. |
| 150 |
tm := timers.AcquireTimer(closeFrameWait) |
| 151 |
select { |
| 152 |
case <-t.graceCh: |
| 153 |
case <-tm.C: |
| 154 |
} |
| 155 |
timers.ReleaseTimer(tm) |
| 156 |
} |
| 157 |
return t.conn.Close() |
| 158 |
} |
| 159 |
return t.conn.Close() |
| 160 |
} |
| 161 |
|
| 162 |
// Defaults. |
| 163 |
const ( |
| 164 |
DefaultWebsocketPingInterval = 25 * time.Second |
| 165 |
DefaultWebsocketWriteTimeout = 1 * time.Second |
| 166 |
DefaultWebsocketMessageSizeLimit = 65536 // 64KB |
| 167 |
) |
| 168 |
|
| 169 |
// WebsocketConfig represents config for WebsocketHandler. |
| 170 |
type WebsocketConfig struct { |
| 171 |
// CompressionLevel sets a level for websocket compression. |
| 172 |
// See possible value description at https://golang.org/pkg/compress/flate/#NewWriter |
| 173 |
CompressionLevel int |
| 174 |
|
| 175 |
// CompressionMinSize allows to set minimal limit in bytes for |
| 176 |
// message to use compression when writing it into client connection. |
| 177 |
// By default it's 0 - i.e. all messages will be compressed when |
| 178 |
// WebsocketCompression enabled and compression negotiated with client. |
| 179 |
CompressionMinSize int |
| 180 |
|
| 181 |
// ReadBufferSize is a parameter that is used for raw websocket Upgrader. |
| 182 |
// If set to zero reasonable default value will be used. |
| 183 |
ReadBufferSize int |
| 184 |
|
| 185 |
// WriteBufferSize is a parameter that is used for raw websocket Upgrader. |
| 186 |
// If set to zero reasonable default value will be used. |
| 187 |
WriteBufferSize int |
| 188 |
|
| 189 |
// MessageSizeLimit sets the maximum size in bytes of allowed message from client. |
| 190 |
// By default DefaultWebsocketMaxMessageSize will be used. |
| 191 |
MessageSizeLimit int |
| 192 |
|
| 193 |
// CheckOrigin func to provide custom origin check logic. |
| 194 |
// nil means allow all origins. |
| 195 |
CheckOrigin func(r *http.Request) bool |
| 196 |
|
| 197 |
// PingInterval sets interval server will send ping messages to clients. |
| 198 |
// By default DefaultPingInterval will be used. |
| 199 |
PingInterval time.Duration |
| 200 |
|
| 201 |
// WriteTimeout is maximum time of write message operation. |
| 202 |
// Slow client will be disconnected. |
| 203 |
// By default DefaultWebsocketWriteTimeout will be used. |
| 204 |
WriteTimeout time.Duration |
| 205 |
|
| 206 |
// Compression allows to enable websocket permessage-deflate |
| 207 |
// compression support for raw websocket connections. It does |
| 208 |
// not guarantee that compression will be used - i.e. it only |
| 209 |
// says that server will try to negotiate it with client. |
| 210 |
Compression bool |
| 211 |
|
| 212 |
// UseWriteBufferPool enables using buffer pool for writes. |
| 213 |
UseWriteBufferPool bool |
| 214 |
} |
| 215 |
|
| 216 |
// WebsocketHandler handles WebSocket client connections. WebSocket protocol |
| 217 |
// is a bidirectional connection between a client an a server for low-latency |
| 218 |
// communication. |
| 219 |
type WebsocketHandler struct { |
| 220 |
node *Node |
| 221 |
upgrade *websocket.Upgrader |
| 222 |
config WebsocketConfig |
| 223 |
} |
| 224 |
|
| 225 |
var writeBufferPool = &sync.Pool{} |
| 226 |
|
| 227 |
// NewWebsocketHandler creates new WebsocketHandler. |
| 228 |
func NewWebsocketHandler(n *Node, c WebsocketConfig) *WebsocketHandler { |
| 229 |
upgrade := &websocket.Upgrader{ |
| 230 |
ReadBufferSize: c.ReadBufferSize, |
| 231 |
EnableCompression: c.Compression, |
| 232 |
} |
| 233 |
if c.UseWriteBufferPool { |
| 234 |
upgrade.WriteBufferPool = writeBufferPool |
| 235 |
} else { |
| 236 |
upgrade.WriteBufferSize = c.WriteBufferSize |
| 237 |
} |
| 238 |
if c.CheckOrigin != nil { |
| 239 |
upgrade.CheckOrigin = c.CheckOrigin |
| 240 |
} else { |
| 241 |
upgrade.CheckOrigin = sameHostOriginCheck(n) |
| 242 |
} |
| 243 |
return &WebsocketHandler{ |
| 244 |
node: n, |
| 245 |
config: c, |
| 246 |
upgrade: upgrade, |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
func (s *WebsocketHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { |
| 251 |
incTransportConnect(transportWebsocket) |
| 252 |
|
| 253 |
compression := s.config.Compression |
| 254 |
compressionLevel := s.config.CompressionLevel |
| 255 |
compressionMinSize := s.config.CompressionMinSize |
| 256 |
|
| 257 |
conn, err := s.upgrade.Upgrade(rw, r, nil) |
| 258 |
if err != nil { |
| 259 |
s.node.logger.log(newLogEntry(LogLevelDebug, "websocket upgrade error", map[string]interface{}{"error": err.Error()})) |
| 260 |
return |
| 261 |
} |
| 262 |
|
| 263 |
if compression { |
| 264 |
err := conn.SetCompressionLevel(compressionLevel) |
| 265 |
if err != nil { |
| 266 |
s.node.logger.log(newLogEntry(LogLevelError, "websocket error setting compression level", map[string]interface{}{"error": err.Error()})) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
pingInterval := s.config.PingInterval |
| 271 |
if pingInterval == 0 { |
| 272 |
pingInterval = DefaultWebsocketPingInterval |
| 273 |
} |
| 274 |
writeTimeout := s.config.WriteTimeout |
| 275 |
if writeTimeout == 0 { |
| 276 |
writeTimeout = DefaultWebsocketWriteTimeout |
| 277 |
} |
| 278 |
messageSizeLimit := s.config.MessageSizeLimit |
| 279 |
if messageSizeLimit == 0 { |
| 280 |
messageSizeLimit = DefaultWebsocketMessageSizeLimit |
| 281 |
} |
| 282 |
|
| 283 |
if messageSizeLimit > 0 { |
| 284 |
conn.SetReadLimit(int64(messageSizeLimit)) |
| 285 |
} |
| 286 |
if pingInterval > 0 { |
| 287 |
pongWait := pingInterval * 10 / 9 |
| 288 |
_ = conn.SetReadDeadline(time.Now().Add(pongWait)) |
| 289 |
conn.SetPongHandler(func(string) error { |
| 290 |
_ = conn.SetReadDeadline(time.Now().Add(pongWait)) |
| 291 |
return nil |
| 292 |
}) |
| 293 |
} |
| 294 |
|
| 295 |
var protocol = ProtocolTypeJSON |
| 296 |
if r.URL.Query().Get("format") == "protobuf" || r.URL.Query().Get("protocol") == "protobuf" { |
| 297 |
protocol = ProtocolTypeProtobuf |
| 298 |
} |
| 299 |
|
| 300 |
var enc = EncodingTypeJSON |
| 301 |
if r.URL.Query().Get("encoding") == "binary" { |
| 302 |
enc = EncodingTypeBinary |
| 303 |
} |
| 304 |
|
| 305 |
// Separate goroutine for better GC of caller's data. |
| 306 |
go func() { |
| 307 |
opts := websocketTransportOptions{ |
| 308 |
pingInterval: pingInterval, |
| 309 |
writeTimeout: writeTimeout, |
| 310 |
compressionMinSize: compressionMinSize, |
| 311 |
encType: enc, |
| 312 |
protoType: protocol, |
| 313 |
} |
| 314 |
|
| 315 |
graceCh := make(chan struct{}) |
| 316 |
transport := newWebsocketTransport(conn, opts, graceCh) |
| 317 |
|
| 318 |
select { |
| 319 |
case <-s.node.NotifyShutdown(): |
| 320 |
_ = transport.Close(DisconnectShutdown) |
| 321 |
return |
| 322 |
default: |
| 323 |
} |
| 324 |
|
| 325 |
ctxCh := make(chan struct{}) |
| 326 |
defer close(ctxCh) |
| 327 |
|
| 328 |
c, closeFn, err := NewClient(cancelctx.New(r.Context(), ctxCh), s.node, transport) |
| 329 |
if err != nil { |
| 330 |
s.node.logger.log(newLogEntry(LogLevelError, "error creating client", map[string]interface{}{"transport": transportWebsocket})) |
| 331 |
return |
| 332 |
} |
| 333 |
defer func() { _ = closeFn() }() |
| 334 |
|
| 335 |
s.node.logger.log(newLogEntry(LogLevelDebug, "client connection established", map[string]interface{}{"client": c.ID(), "transport": transportWebsocket})) |
| 336 |
defer func(started time.Time) { |
| 337 |
s.node.logger.log(newLogEntry(LogLevelDebug, "client connection completed", map[string]interface{}{"client": c.ID(), "transport": transportWebsocket, "duration": time.Since(started)})) |
| 338 |
}(time.Now()) |
| 339 |
|
| 340 |
for { |
| 341 |
_, data, err := conn.ReadMessage() |
| 342 |
if err != nil { |
| 343 |
break |
| 344 |
} |
| 345 |
closed := !c.Handle(data) |
| 346 |
if closed { |
| 347 |
break |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
// https://github.com/gorilla/websocket/issues/448 |
| 352 |
conn.SetPingHandler(nil) |
| 353 |
conn.SetPongHandler(nil) |
| 354 |
conn.SetCloseHandler(nil) |
| 355 |
_ = conn.SetReadDeadline(time.Now().Add(closeFrameWait)) |
| 356 |
for { |
| 357 |
if _, _, err := conn.NextReader(); err != nil { |
| 358 |
close(graceCh) |
| 359 |
break |
| 360 |
} |
| 361 |
} |
| 362 |
}() |
| 363 |
} |
| 364 |
|
| 365 |
func sameHostOriginCheck(n *Node) func(r *http.Request) bool { |
| 366 |
return func(r *http.Request) bool { |
| 367 |
err := checkSameHost(r) |
| 368 |
if err != nil { |
| 369 |
n.logger.log(newLogEntry(LogLevelInfo, "origin check failure", map[string]interface{}{"error": err.Error()})) |
| 370 |
return false |
| 371 |
} |
| 372 |
return true |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
func checkSameHost(r *http.Request) error { |
| 377 |
origin := r.Header.Get("Origin") |
| 378 |
if origin == "" { |
| 379 |
return nil |
| 380 |
} |
| 381 |
u, err := url.Parse(origin) |
| 382 |
if err != nil { |
| 383 |
return fmt.Errorf("failed to parse Origin header %q: %w", origin, err) |
| 384 |
} |
| 385 |
if strings.EqualFold(r.Host, u.Host) { |
| 386 |
return nil |
| 387 |
} |
| 388 |
return fmt.Errorf("request Origin %q is not authorized for Host %q", origin, r.Host) |
| 389 |
} |