github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/rpc/websocket.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rpc 18 19 import ( 20 "context" 21 "encoding/base64" 22 "fmt" 23 "net/http" 24 "net/url" 25 "os" 26 "strings" 27 "sync" 28 "time" 29 30 mapset "github.com/deckarep/golang-set/v2" 31 "github.com/gorilla/websocket" 32 "github.com/tirogen/go-ethereum/log" 33 ) 34 35 const ( 36 wsReadBuffer = 1024 37 wsWriteBuffer = 1024 38 wsPingInterval = 30 * time.Second 39 wsPingWriteTimeout = 5 * time.Second 40 wsPongTimeout = 30 * time.Second 41 wsMessageSizeLimit = 15 * 1024 * 1024 42 ) 43 44 var wsBufferPool = new(sync.Pool) 45 46 // WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections. 47 // 48 // allowedOrigins should be a comma-separated list of allowed origin URLs. 49 // To allow connections with any origin, pass "*". 50 func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler { 51 var upgrader = websocket.Upgrader{ 52 ReadBufferSize: wsReadBuffer, 53 WriteBufferSize: wsWriteBuffer, 54 WriteBufferPool: wsBufferPool, 55 CheckOrigin: wsHandshakeValidator(allowedOrigins), 56 } 57 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 58 conn, err := upgrader.Upgrade(w, r, nil) 59 if err != nil { 60 log.Debug("WebSocket upgrade failed", "err", err) 61 return 62 } 63 codec := newWebsocketCodec(conn, r.Host, r.Header) 64 s.ServeCodec(codec, 0) 65 }) 66 } 67 68 // wsHandshakeValidator returns a handler that verifies the origin during the 69 // websocket upgrade process. When a '*' is specified as an allowed origins all 70 // connections are accepted. 71 func wsHandshakeValidator(allowedOrigins []string) func(*http.Request) bool { 72 origins := mapset.NewSet[string]() 73 allowAllOrigins := false 74 75 for _, origin := range allowedOrigins { 76 if origin == "*" { 77 allowAllOrigins = true 78 } 79 if origin != "" { 80 origins.Add(origin) 81 } 82 } 83 // allow localhost if no allowedOrigins are specified. 84 if len(origins.ToSlice()) == 0 { 85 origins.Add("http://localhost") 86 if hostname, err := os.Hostname(); err == nil { 87 origins.Add("http://" + hostname) 88 } 89 } 90 log.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v", origins.ToSlice())) 91 92 f := func(req *http.Request) bool { 93 // Skip origin verification if no Origin header is present. The origin check 94 // is supposed to protect against browser based attacks. Browsers always set 95 // Origin. Non-browser software can put anything in origin and checking it doesn't 96 // provide additional security. 97 if _, ok := req.Header["Origin"]; !ok { 98 return true 99 } 100 // Verify origin against allow list. 101 origin := strings.ToLower(req.Header.Get("Origin")) 102 if allowAllOrigins || originIsAllowed(origins, origin) { 103 return true 104 } 105 log.Warn("Rejected WebSocket connection", "origin", origin) 106 return false 107 } 108 109 return f 110 } 111 112 type wsHandshakeError struct { 113 err error 114 status string 115 } 116 117 func (e wsHandshakeError) Error() string { 118 s := e.err.Error() 119 if e.status != "" { 120 s += " (HTTP status " + e.status + ")" 121 } 122 return s 123 } 124 125 func originIsAllowed(allowedOrigins mapset.Set[string], browserOrigin string) bool { 126 it := allowedOrigins.Iterator() 127 for origin := range it.C { 128 if ruleAllowsOrigin(origin, browserOrigin) { 129 return true 130 } 131 } 132 return false 133 } 134 135 func ruleAllowsOrigin(allowedOrigin string, browserOrigin string) bool { 136 var ( 137 allowedScheme, allowedHostname, allowedPort string 138 browserScheme, browserHostname, browserPort string 139 err error 140 ) 141 allowedScheme, allowedHostname, allowedPort, err = parseOriginURL(allowedOrigin) 142 if err != nil { 143 log.Warn("Error parsing allowed origin specification", "spec", allowedOrigin, "error", err) 144 return false 145 } 146 browserScheme, browserHostname, browserPort, err = parseOriginURL(browserOrigin) 147 if err != nil { 148 log.Warn("Error parsing browser 'Origin' field", "Origin", browserOrigin, "error", err) 149 return false 150 } 151 if allowedScheme != "" && allowedScheme != browserScheme { 152 return false 153 } 154 if allowedHostname != "" && allowedHostname != browserHostname { 155 return false 156 } 157 if allowedPort != "" && allowedPort != browserPort { 158 return false 159 } 160 return true 161 } 162 163 func parseOriginURL(origin string) (string, string, string, error) { 164 parsedURL, err := url.Parse(strings.ToLower(origin)) 165 if err != nil { 166 return "", "", "", err 167 } 168 var scheme, hostname, port string 169 if strings.Contains(origin, "://") { 170 scheme = parsedURL.Scheme 171 hostname = parsedURL.Hostname() 172 port = parsedURL.Port() 173 } else { 174 scheme = "" 175 hostname = parsedURL.Scheme 176 port = parsedURL.Opaque 177 if hostname == "" { 178 hostname = origin 179 } 180 } 181 return scheme, hostname, port, nil 182 } 183 184 // DialWebsocketWithDialer creates a new RPC client using WebSocket. 185 // 186 // The context is used for the initial connection establishment. It does not 187 // affect subsequent interactions with the client. 188 // 189 // Deprecated: use DialOptions and the WithWebsocketDialer option. 190 func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error) { 191 cfg := new(clientConfig) 192 cfg.wsDialer = &dialer 193 if origin != "" { 194 cfg.setHeader("origin", origin) 195 } 196 connect, err := newClientTransportWS(endpoint, cfg) 197 if err != nil { 198 return nil, err 199 } 200 return newClient(ctx, connect) 201 } 202 203 // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server 204 // that is listening on the given endpoint. 205 // 206 // The context is used for the initial connection establishment. It does not 207 // affect subsequent interactions with the client. 208 func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) { 209 cfg := new(clientConfig) 210 if origin != "" { 211 cfg.setHeader("origin", origin) 212 } 213 connect, err := newClientTransportWS(endpoint, cfg) 214 if err != nil { 215 return nil, err 216 } 217 return newClient(ctx, connect) 218 } 219 220 func newClientTransportWS(endpoint string, cfg *clientConfig) (reconnectFunc, error) { 221 dialer := cfg.wsDialer 222 if dialer == nil { 223 dialer = &websocket.Dialer{ 224 ReadBufferSize: wsReadBuffer, 225 WriteBufferSize: wsWriteBuffer, 226 WriteBufferPool: wsBufferPool, 227 } 228 } 229 230 dialURL, header, err := wsClientHeaders(endpoint, "") 231 if err != nil { 232 return nil, err 233 } 234 for key, values := range cfg.httpHeaders { 235 header[key] = values 236 } 237 238 connect := func(ctx context.Context) (ServerCodec, error) { 239 header := header.Clone() 240 if cfg.httpAuth != nil { 241 if err := cfg.httpAuth(header); err != nil { 242 return nil, err 243 } 244 } 245 conn, resp, err := dialer.DialContext(ctx, dialURL, header) 246 if err != nil { 247 hErr := wsHandshakeError{err: err} 248 if resp != nil { 249 hErr.status = resp.Status 250 } 251 return nil, hErr 252 } 253 return newWebsocketCodec(conn, dialURL, header), nil 254 } 255 return connect, nil 256 } 257 258 func wsClientHeaders(endpoint, origin string) (string, http.Header, error) { 259 endpointURL, err := url.Parse(endpoint) 260 if err != nil { 261 return endpoint, nil, err 262 } 263 header := make(http.Header) 264 if origin != "" { 265 header.Add("origin", origin) 266 } 267 if endpointURL.User != nil { 268 b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String())) 269 header.Add("authorization", "Basic "+b64auth) 270 endpointURL.User = nil 271 } 272 return endpointURL.String(), header, nil 273 } 274 275 type websocketCodec struct { 276 *jsonCodec 277 conn *websocket.Conn 278 info PeerInfo 279 280 wg sync.WaitGroup 281 pingReset chan struct{} 282 } 283 284 func newWebsocketCodec(conn *websocket.Conn, host string, req http.Header) ServerCodec { 285 conn.SetReadLimit(wsMessageSizeLimit) 286 conn.SetPongHandler(func(appData string) error { 287 conn.SetReadDeadline(time.Time{}) 288 return nil 289 }) 290 291 encode := func(v interface{}, isErrorResponse bool) error { 292 return conn.WriteJSON(v) 293 } 294 wc := &websocketCodec{ 295 jsonCodec: NewFuncCodec(conn, encode, conn.ReadJSON).(*jsonCodec), 296 conn: conn, 297 pingReset: make(chan struct{}, 1), 298 info: PeerInfo{ 299 Transport: "ws", 300 RemoteAddr: conn.RemoteAddr().String(), 301 }, 302 } 303 // Fill in connection details. 304 wc.info.HTTP.Host = host 305 wc.info.HTTP.Origin = req.Get("Origin") 306 wc.info.HTTP.UserAgent = req.Get("User-Agent") 307 // Start pinger. 308 wc.wg.Add(1) 309 go wc.pingLoop() 310 return wc 311 } 312 313 func (wc *websocketCodec) close() { 314 wc.jsonCodec.close() 315 wc.wg.Wait() 316 } 317 318 func (wc *websocketCodec) peerInfo() PeerInfo { 319 return wc.info 320 } 321 322 func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}, isError bool) error { 323 err := wc.jsonCodec.writeJSON(ctx, v, isError) 324 if err == nil { 325 // Notify pingLoop to delay the next idle ping. 326 select { 327 case wc.pingReset <- struct{}{}: 328 default: 329 } 330 } 331 return err 332 } 333 334 // pingLoop sends periodic ping frames when the connection is idle. 335 func (wc *websocketCodec) pingLoop() { 336 var timer = time.NewTimer(wsPingInterval) 337 defer wc.wg.Done() 338 defer timer.Stop() 339 340 for { 341 select { 342 case <-wc.closed(): 343 return 344 case <-wc.pingReset: 345 if !timer.Stop() { 346 <-timer.C 347 } 348 timer.Reset(wsPingInterval) 349 case <-timer.C: 350 wc.jsonCodec.encMu.Lock() 351 wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout)) 352 wc.conn.WriteMessage(websocket.PingMessage, nil) 353 wc.conn.SetReadDeadline(time.Now().Add(wsPongTimeout)) 354 wc.jsonCodec.encMu.Unlock() 355 timer.Reset(wsPingInterval) 356 } 357 } 358 }