| 1 |
package centrifuge |
| 2 |
|
| 3 |
import ( |
| 4 |
"net/http" |
| 5 |
"sync" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/centrifugal/centrifuge/internal/cancelctx" |
| 9 |
|
| 10 |
"github.com/gorilla/websocket" |
| 11 |
"github.com/igm/sockjs-go/v3/sockjs" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
transportSockJS = "sockjs" |
| 16 |
) |
| 17 |
|
| 18 |
type sockjsTransport struct { |
| 19 |
mu sync.RWMutex |
| 20 |
closed bool |
| 21 |
closeCh chan struct{} |
| 22 |
session sockjs.Session |
| 23 |
} |
| 24 |
|
| 25 |
func newSockjsTransport(s sockjs.Session) *sockjsTransport { |
| 26 |
t := &sockjsTransport{ |
| 27 |
session: s, |
| 28 |
closeCh: make(chan struct{}), |
| 29 |
} |
| 30 |
return t |
| 31 |
} |
| 32 |
|
| 33 |
// Name returns name of transport. |
| 34 |
func (t *sockjsTransport) Name() string { |
| 35 |
return transportSockJS |
| 36 |
} |
| 37 |
|
| 38 |
// Protocol returns transport protocol. |
| 39 |
func (t *sockjsTransport) Protocol() ProtocolType { |
| 40 |
return ProtocolTypeJSON |
| 41 |
} |
| 42 |
|
| 43 |
// Encoding returns transport encoding. |
| 44 |
func (t *sockjsTransport) Encoding() EncodingType { |
| 45 |
return EncodingTypeJSON |
| 46 |
} |
| 47 |
|
| 48 |
// Write data to transport. |
| 49 |
func (t *sockjsTransport) Write(data []byte) error { |
| 50 |
select { |
| 51 |
case <-t.closeCh: |
| 52 |
return nil |
| 53 |
default: |
| 54 |
return t.session.Send(string(data)) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
// Close closes transport. |
| 59 |
func (t *sockjsTransport) Close(disconnect *Disconnect) error { |
| 60 |
t.mu.Lock() |
| 61 |
if t.closed { |
| 62 |
// Already closed, noop. |
| 63 |
t.mu.Unlock() |
| 64 |
return nil |
| 65 |
} |
| 66 |
t.closed = true |
| 67 |
close(t.closeCh) |
| 68 |
t.mu.Unlock() |
| 69 |
|
| 70 |
if disconnect == nil { |
| 71 |
disconnect = DisconnectNormal |
| 72 |
} |
| 73 |
return t.session.Close(disconnect.Code, disconnect.CloseText()) |
| 74 |
} |
| 75 |
|
| 76 |
// SockjsConfig represents config for SockJS handler. |
| 77 |
type SockjsConfig struct { |
| 78 |
// HandlerPrefix sets prefix for SockJS handler endpoint path. |
| 79 |
HandlerPrefix string |
| 80 |
|
| 81 |
// URL is an address to SockJS client javascript library. |
| 82 |
URL string |
| 83 |
|
| 84 |
// HeartbeatDelay sets how often to send heartbeat frames to clients. |
| 85 |
HeartbeatDelay time.Duration |
| 86 |
|
| 87 |
// CheckOrigin allows to decide whether to use CORS or not in XHR case. |
| 88 |
// When false returned then CORS headers won't be set. |
| 89 |
CheckOrigin func(*http.Request) bool |
| 90 |
|
| 91 |
// WebsocketCheckOrigin allows to set custom CheckOrigin func for underlying |
| 92 |
// Gorilla Websocket based websocket.Upgrader. |
| 93 |
WebsocketCheckOrigin func(*http.Request) bool |
| 94 |
|
| 95 |
// WebsocketReadBufferSize is a parameter that is used for raw websocket websocket.Upgrader. |
| 96 |
// If set to zero reasonable default value will be used. |
| 97 |
WebsocketReadBufferSize int |
| 98 |
|
| 99 |
// WebsocketWriteBufferSize is a parameter that is used for raw websocket websocket.Upgrader. |
| 100 |
// If set to zero reasonable default value will be used. |
| 101 |
WebsocketWriteBufferSize int |
| 102 |
|
| 103 |
// WebsocketUseWriteBufferPool enables using buffer pool for writes in Websocket transport. |
| 104 |
WebsocketUseWriteBufferPool bool |
| 105 |
|
| 106 |
// WebsocketWriteTimeout is maximum time of write message operation. |
| 107 |
// Slow client will be disconnected. |
| 108 |
// By default DefaultWebsocketWriteTimeout will be used. |
| 109 |
WebsocketWriteTimeout time.Duration |
| 110 |
} |
| 111 |
|
| 112 |
// SockjsHandler accepts SockJS connections. SockJS has a bunch of fallback |
| 113 |
// transports when WebSocket connection is not supported. It comes with additional |
| 114 |
// costs though: small protocol framing overhead, lack of binary support, more |
| 115 |
// goroutines per connection, and you need to use sticky session mechanism on |
| 116 |
// your load balancer in case you are using HTTP-based SockJS fallbacks and have |
| 117 |
// more than one Centrifuge Node on a backend (so SockJS to be able to emulate |
| 118 |
// bidirectional protocol). So if you can afford it - use WebsocketHandler only. |
| 119 |
type SockjsHandler struct { |
| 120 |
node *Node |
| 121 |
config SockjsConfig |
| 122 |
handler http.Handler |
| 123 |
} |
| 124 |
|
| 125 |
// NewSockjsHandler creates new SockjsHandler. |
| 126 |
func NewSockjsHandler(n *Node, c SockjsConfig) *SockjsHandler { |
| 127 |
options := sockjs.DefaultOptions |
| 128 |
wsUpgrader := &websocket.Upgrader{ |
| 129 |
ReadBufferSize: c.WebsocketReadBufferSize, |
| 130 |
WriteBufferSize: c.WebsocketWriteBufferSize, |
| 131 |
Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) {}, |
| 132 |
} |
| 133 |
if c.WebsocketCheckOrigin != nil { |
| 134 |
wsUpgrader.CheckOrigin = c.WebsocketCheckOrigin |
| 135 |
} else { |
| 136 |
wsUpgrader.CheckOrigin = sameHostOriginCheck(n) |
| 137 |
} |
| 138 |
if c.WebsocketUseWriteBufferPool { |
| 139 |
wsUpgrader.WriteBufferPool = writeBufferPool |
| 140 |
} else { |
| 141 |
wsUpgrader.WriteBufferSize = c.WebsocketWriteBufferSize |
| 142 |
} |
| 143 |
options.WebsocketUpgrader = wsUpgrader |
| 144 |
// Override sockjs url. It's important to use the same SockJS |
| 145 |
// library version on client and server sides when using iframe |
| 146 |
// based SockJS transports, otherwise SockJS will raise error |
| 147 |
// about version mismatch. |
| 148 |
options.SockJSURL = c.URL |
| 149 |
if c.CheckOrigin != nil { |
| 150 |
options.CheckOrigin = c.CheckOrigin |
| 151 |
} else { |
| 152 |
options.CheckOrigin = sameHostOriginCheck(n) |
| 153 |
} |
| 154 |
|
| 155 |
options.HeartbeatDelay = c.HeartbeatDelay |
| 156 |
wsWriteTimeout := c.WebsocketWriteTimeout |
| 157 |
if wsWriteTimeout == 0 { |
| 158 |
wsWriteTimeout = DefaultWebsocketWriteTimeout |
| 159 |
} |
| 160 |
options.WebsocketWriteTimeout = wsWriteTimeout |
| 161 |
|
| 162 |
s := &SockjsHandler{ |
| 163 |
node: n, |
| 164 |
config: c, |
| 165 |
} |
| 166 |
|
| 167 |
handler := newSockJSHandler(s, c.HandlerPrefix, options) |
| 168 |
s.handler = handler |
| 169 |
return s |
| 170 |
} |
| 171 |
|
| 172 |
func (s *SockjsHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { |
| 173 |
s.handler.ServeHTTP(rw, r) |
| 174 |
} |
| 175 |
|
| 176 |
// newSockJSHandler returns SockJS handler bind to sockjsPrefix url prefix. |
| 177 |
// SockJS handler has several handlers inside responsible for various tasks |
| 178 |
// according to SockJS protocol. |
| 179 |
func newSockJSHandler(s *SockjsHandler, sockjsPrefix string, sockjsOpts sockjs.Options) http.Handler { |
| 180 |
return sockjs.NewHandler(sockjsPrefix, sockjsOpts, s.sockJSHandler) |
| 181 |
} |
| 182 |
|
| 183 |
// sockJSHandler called when new client connection comes to SockJS endpoint. |
| 184 |
func (s *SockjsHandler) sockJSHandler(sess sockjs.Session) { |
| 185 |
incTransportConnect(transportSockJS) |
| 186 |
|
| 187 |
// Separate goroutine for better GC of caller's data. |
| 188 |
go func() { |
| 189 |
transport := newSockjsTransport(sess) |
| 190 |
|
| 191 |
select { |
| 192 |
case <-s.node.NotifyShutdown(): |
| 193 |
_ = transport.Close(DisconnectShutdown) |
| 194 |
return |
| 195 |
default: |
| 196 |
} |
| 197 |
|
| 198 |
ctxCh := make(chan struct{}) |
| 199 |
defer close(ctxCh) |
| 200 |
c, closeFn, err := NewClient(cancelctx.New(sess.Request().Context(), ctxCh), s.node, transport) |
| 201 |
if err != nil { |
| 202 |
s.node.logger.log(newLogEntry(LogLevelError, "error creating client", map[string]interface{}{"transport": transportSockJS})) |
| 203 |
return |
| 204 |
} |
| 205 |
defer func() { _ = closeFn() }() |
| 206 |
s.node.logger.log(newLogEntry(LogLevelDebug, "client connection established", map[string]interface{}{"client": c.ID(), "transport": transportSockJS})) |
| 207 |
defer func(started time.Time) { |
| 208 |
s.node.logger.log(newLogEntry(LogLevelDebug, "client connection completed", map[string]interface{}{"client": c.ID(), "transport": transportSockJS, "duration": time.Since(started)})) |
| 209 |
}(time.Now()) |
| 210 |
|
| 211 |
var needWaitLoop bool |
| 212 |
|
| 213 |
for { |
| 214 |
if msg, err := sess.Recv(); err == nil { |
| 215 |
if ok := c.Handle([]byte(msg)); !ok { |
| 216 |
needWaitLoop = true |
| 217 |
break |
| 218 |
} |
| 219 |
continue |
| 220 |
} |
| 221 |
break |
| 222 |
} |
| 223 |
|
| 224 |
if needWaitLoop { |
| 225 |
// One extra loop till we get an error from session, |
| 226 |
// this is required to wait until close frame will be sent |
| 227 |
// into connection inside Client implementation and transport |
| 228 |
// closed with proper disconnect reason. |
| 229 |
for { |
| 230 |
if _, err := sess.Recv(); err != nil { |
| 231 |
break |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
}() |
| 236 |
} |