github.com/theQRL/go-zond@v0.1.1/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/theQRL/go-zond/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 = 32 * 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, cfg, 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, cfg, 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  			Proxy:           http.ProxyFromEnvironment,
   228  		}
   229  	}
   230  
   231  	dialURL, header, err := wsClientHeaders(endpoint, "")
   232  	if err != nil {
   233  		return nil, err
   234  	}
   235  	for key, values := range cfg.httpHeaders {
   236  		header[key] = values
   237  	}
   238  
   239  	connect := func(ctx context.Context) (ServerCodec, error) {
   240  		header := header.Clone()
   241  		if cfg.httpAuth != nil {
   242  			if err := cfg.httpAuth(header); err != nil {
   243  				return nil, err
   244  			}
   245  		}
   246  		conn, resp, err := dialer.DialContext(ctx, dialURL, header)
   247  		if err != nil {
   248  			hErr := wsHandshakeError{err: err}
   249  			if resp != nil {
   250  				hErr.status = resp.Status
   251  			}
   252  			return nil, hErr
   253  		}
   254  		return newWebsocketCodec(conn, dialURL, header), nil
   255  	}
   256  	return connect, nil
   257  }
   258  
   259  func wsClientHeaders(endpoint, origin string) (string, http.Header, error) {
   260  	endpointURL, err := url.Parse(endpoint)
   261  	if err != nil {
   262  		return endpoint, nil, err
   263  	}
   264  	header := make(http.Header)
   265  	if origin != "" {
   266  		header.Add("origin", origin)
   267  	}
   268  	if endpointURL.User != nil {
   269  		b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String()))
   270  		header.Add("authorization", "Basic "+b64auth)
   271  		endpointURL.User = nil
   272  	}
   273  	return endpointURL.String(), header, nil
   274  }
   275  
   276  type websocketCodec struct {
   277  	*jsonCodec
   278  	conn *websocket.Conn
   279  	info PeerInfo
   280  
   281  	wg           sync.WaitGroup
   282  	pingReset    chan struct{}
   283  	pongReceived chan struct{}
   284  }
   285  
   286  func newWebsocketCodec(conn *websocket.Conn, host string, req http.Header) ServerCodec {
   287  	conn.SetReadLimit(wsMessageSizeLimit)
   288  	encode := func(v interface{}, isErrorResponse bool) error {
   289  		return conn.WriteJSON(v)
   290  	}
   291  	wc := &websocketCodec{
   292  		jsonCodec:    NewFuncCodec(conn, encode, conn.ReadJSON).(*jsonCodec),
   293  		conn:         conn,
   294  		pingReset:    make(chan struct{}, 1),
   295  		pongReceived: make(chan struct{}),
   296  		info: PeerInfo{
   297  			Transport:  "ws",
   298  			RemoteAddr: conn.RemoteAddr().String(),
   299  		},
   300  	}
   301  	// Fill in connection details.
   302  	wc.info.HTTP.Host = host
   303  	wc.info.HTTP.Origin = req.Get("Origin")
   304  	wc.info.HTTP.UserAgent = req.Get("User-Agent")
   305  	// Start pinger.
   306  	conn.SetPongHandler(func(appData string) error {
   307  		select {
   308  		case wc.pongReceived <- struct{}{}:
   309  		case <-wc.closed():
   310  		}
   311  		return nil
   312  	})
   313  	wc.wg.Add(1)
   314  	go wc.pingLoop()
   315  	return wc
   316  }
   317  
   318  func (wc *websocketCodec) close() {
   319  	wc.jsonCodec.close()
   320  	wc.wg.Wait()
   321  }
   322  
   323  func (wc *websocketCodec) peerInfo() PeerInfo {
   324  	return wc.info
   325  }
   326  
   327  func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}, isError bool) error {
   328  	err := wc.jsonCodec.writeJSON(ctx, v, isError)
   329  	if err == nil {
   330  		// Notify pingLoop to delay the next idle ping.
   331  		select {
   332  		case wc.pingReset <- struct{}{}:
   333  		default:
   334  		}
   335  	}
   336  	return err
   337  }
   338  
   339  // pingLoop sends periodic ping frames when the connection is idle.
   340  func (wc *websocketCodec) pingLoop() {
   341  	var pingTimer = time.NewTimer(wsPingInterval)
   342  	defer wc.wg.Done()
   343  	defer pingTimer.Stop()
   344  
   345  	for {
   346  		select {
   347  		case <-wc.closed():
   348  			return
   349  
   350  		case <-wc.pingReset:
   351  			if !pingTimer.Stop() {
   352  				<-pingTimer.C
   353  			}
   354  			pingTimer.Reset(wsPingInterval)
   355  
   356  		case <-pingTimer.C:
   357  			wc.jsonCodec.encMu.Lock()
   358  			wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout))
   359  			wc.conn.WriteMessage(websocket.PingMessage, nil)
   360  			wc.conn.SetReadDeadline(time.Now().Add(wsPongTimeout))
   361  			wc.jsonCodec.encMu.Unlock()
   362  			pingTimer.Reset(wsPingInterval)
   363  
   364  		case <-wc.pongReceived:
   365  			wc.conn.SetReadDeadline(time.Time{})
   366  		}
   367  	}
   368  }