github.com/LampardNguyen234/go-ethereum@v1.10.16-0.20220117140830-b6a3b0260724/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 "github.com/LampardNguyen234/go-ethereum/log" 31 mapset "github.com/deckarep/golang-set" 32 "github.com/gorilla/websocket" 33 ) 34 35 const ( 36 wsReadBuffer = 1024 37 wsWriteBuffer = 1024 38 wsPingInterval = 60 * 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) 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() 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, browserOrigin string) bool { 126 it := allowedOrigins.Iterator() 127 for origin := range it.C { 128 if ruleAllowsOrigin(origin.(string), 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 that communicates with a JSON-RPC server 185 // that is listening on the given endpoint using the provided dialer. 186 func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error) { 187 endpoint, header, err := wsClientHeaders(endpoint, origin) 188 if err != nil { 189 return nil, err 190 } 191 return newClient(ctx, func(ctx context.Context) (ServerCodec, error) { 192 conn, resp, err := dialer.DialContext(ctx, endpoint, header) 193 if err != nil { 194 hErr := wsHandshakeError{err: err} 195 if resp != nil { 196 hErr.status = resp.Status 197 } 198 return nil, hErr 199 } 200 return newWebsocketCodec(conn), nil 201 }) 202 } 203 204 // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server 205 // that is listening on the given endpoint. 206 // 207 // The context is used for the initial connection establishment. It does not 208 // affect subsequent interactions with the client. 209 func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) { 210 dialer := websocket.Dialer{ 211 ReadBufferSize: wsReadBuffer, 212 WriteBufferSize: wsWriteBuffer, 213 WriteBufferPool: wsBufferPool, 214 } 215 return DialWebsocketWithDialer(ctx, endpoint, origin, dialer) 216 } 217 218 func wsClientHeaders(endpoint, origin string) (string, http.Header, error) { 219 endpointURL, err := url.Parse(endpoint) 220 if err != nil { 221 return endpoint, nil, err 222 } 223 header := make(http.Header) 224 if origin != "" { 225 header.Add("origin", origin) 226 } 227 if endpointURL.User != nil { 228 b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String())) 229 header.Add("authorization", "Basic "+b64auth) 230 endpointURL.User = nil 231 } 232 return endpointURL.String(), header, nil 233 } 234 235 type websocketCodec struct { 236 *jsonCodec 237 conn *websocket.Conn 238 239 wg sync.WaitGroup 240 pingReset chan struct{} 241 } 242 243 func newWebsocketCodec(conn *websocket.Conn) ServerCodec { 244 conn.SetReadLimit(wsMessageSizeLimit) 245 conn.SetPongHandler(func(appData string) error { 246 conn.SetReadDeadline(time.Time{}) 247 return nil 248 }) 249 wc := &websocketCodec{ 250 jsonCodec: NewFuncCodec(conn, conn.WriteJSON, conn.ReadJSON).(*jsonCodec), 251 conn: conn, 252 pingReset: make(chan struct{}, 1), 253 } 254 wc.wg.Add(1) 255 go wc.pingLoop() 256 return wc 257 } 258 259 func (wc *websocketCodec) close() { 260 wc.jsonCodec.close() 261 wc.wg.Wait() 262 } 263 264 func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}) error { 265 err := wc.jsonCodec.writeJSON(ctx, v) 266 if err == nil { 267 // Notify pingLoop to delay the next idle ping. 268 select { 269 case wc.pingReset <- struct{}{}: 270 default: 271 } 272 } 273 return err 274 } 275 276 // pingLoop sends periodic ping frames when the connection is idle. 277 func (wc *websocketCodec) pingLoop() { 278 var timer = time.NewTimer(wsPingInterval) 279 defer wc.wg.Done() 280 defer timer.Stop() 281 282 for { 283 select { 284 case <-wc.closed(): 285 return 286 case <-wc.pingReset: 287 if !timer.Stop() { 288 <-timer.C 289 } 290 timer.Reset(wsPingInterval) 291 case <-timer.C: 292 wc.jsonCodec.encMu.Lock() 293 wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout)) 294 wc.conn.WriteMessage(websocket.PingMessage, nil) 295 wc.conn.SetReadDeadline(time.Now().Add(wsPongTimeout)) 296 wc.jsonCodec.encMu.Unlock() 297 timer.Reset(wsPingInterval) 298 } 299 } 300 }