github.com/theQRL/go-zond@v0.2.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)
    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  // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server
   185  // that is listening on the given endpoint.
   186  //
   187  // The context is used for the initial connection establishment. It does not
   188  // affect subsequent interactions with the client.
   189  func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) {
   190  	cfg := new(clientConfig)
   191  	if origin != "" {
   192  		cfg.setHeader("origin", origin)
   193  	}
   194  	connect, err := newClientTransportWS(endpoint, cfg)
   195  	if err != nil {
   196  		return nil, err
   197  	}
   198  	return newClient(ctx, cfg, connect)
   199  }
   200  
   201  func newClientTransportWS(endpoint string, cfg *clientConfig) (reconnectFunc, error) {
   202  	dialer := cfg.wsDialer
   203  	if dialer == nil {
   204  		dialer = &websocket.Dialer{
   205  			ReadBufferSize:  wsReadBuffer,
   206  			WriteBufferSize: wsWriteBuffer,
   207  			WriteBufferPool: wsBufferPool,
   208  			Proxy:           http.ProxyFromEnvironment,
   209  		}
   210  	}
   211  
   212  	dialURL, header, err := wsClientHeaders(endpoint, "")
   213  	if err != nil {
   214  		return nil, err
   215  	}
   216  	for key, values := range cfg.httpHeaders {
   217  		header[key] = values
   218  	}
   219  
   220  	connect := func(ctx context.Context) (ServerCodec, error) {
   221  		header := header.Clone()
   222  		if cfg.httpAuth != nil {
   223  			if err := cfg.httpAuth(header); err != nil {
   224  				return nil, err
   225  			}
   226  		}
   227  		conn, resp, err := dialer.DialContext(ctx, dialURL, header)
   228  		if err != nil {
   229  			hErr := wsHandshakeError{err: err}
   230  			if resp != nil {
   231  				hErr.status = resp.Status
   232  			}
   233  			return nil, hErr
   234  		}
   235  		return newWebsocketCodec(conn, dialURL, header), nil
   236  	}
   237  	return connect, nil
   238  }
   239  
   240  func wsClientHeaders(endpoint, origin string) (string, http.Header, error) {
   241  	endpointURL, err := url.Parse(endpoint)
   242  	if err != nil {
   243  		return endpoint, nil, err
   244  	}
   245  	header := make(http.Header)
   246  	if origin != "" {
   247  		header.Add("origin", origin)
   248  	}
   249  	if endpointURL.User != nil {
   250  		b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String()))
   251  		header.Add("authorization", "Basic "+b64auth)
   252  		endpointURL.User = nil
   253  	}
   254  	return endpointURL.String(), header, nil
   255  }
   256  
   257  type websocketCodec struct {
   258  	*jsonCodec
   259  	conn *websocket.Conn
   260  	info PeerInfo
   261  
   262  	wg           sync.WaitGroup
   263  	pingReset    chan struct{}
   264  	pongReceived chan struct{}
   265  }
   266  
   267  func newWebsocketCodec(conn *websocket.Conn, host string, req http.Header) ServerCodec {
   268  	conn.SetReadLimit(wsMessageSizeLimit)
   269  	encode := func(v interface{}, isErrorResponse bool) error {
   270  		return conn.WriteJSON(v)
   271  	}
   272  	wc := &websocketCodec{
   273  		jsonCodec:    NewFuncCodec(conn, encode, conn.ReadJSON).(*jsonCodec),
   274  		conn:         conn,
   275  		pingReset:    make(chan struct{}, 1),
   276  		pongReceived: make(chan struct{}),
   277  		info: PeerInfo{
   278  			Transport:  "ws",
   279  			RemoteAddr: conn.RemoteAddr().String(),
   280  		},
   281  	}
   282  	// Fill in connection details.
   283  	wc.info.HTTP.Host = host
   284  	wc.info.HTTP.Origin = req.Get("Origin")
   285  	wc.info.HTTP.UserAgent = req.Get("User-Agent")
   286  	// Start pinger.
   287  	conn.SetPongHandler(func(appData string) error {
   288  		select {
   289  		case wc.pongReceived <- struct{}{}:
   290  		case <-wc.closed():
   291  		}
   292  		return nil
   293  	})
   294  	wc.wg.Add(1)
   295  	go wc.pingLoop()
   296  	return wc
   297  }
   298  
   299  func (wc *websocketCodec) close() {
   300  	wc.jsonCodec.close()
   301  	wc.wg.Wait()
   302  }
   303  
   304  func (wc *websocketCodec) peerInfo() PeerInfo {
   305  	return wc.info
   306  }
   307  
   308  func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}, isError bool) error {
   309  	err := wc.jsonCodec.writeJSON(ctx, v, isError)
   310  	if err == nil {
   311  		// Notify pingLoop to delay the next idle ping.
   312  		select {
   313  		case wc.pingReset <- struct{}{}:
   314  		default:
   315  		}
   316  	}
   317  	return err
   318  }
   319  
   320  // pingLoop sends periodic ping frames when the connection is idle.
   321  func (wc *websocketCodec) pingLoop() {
   322  	var pingTimer = time.NewTimer(wsPingInterval)
   323  	defer wc.wg.Done()
   324  	defer pingTimer.Stop()
   325  
   326  	for {
   327  		select {
   328  		case <-wc.closed():
   329  			return
   330  
   331  		case <-wc.pingReset:
   332  			if !pingTimer.Stop() {
   333  				<-pingTimer.C
   334  			}
   335  			pingTimer.Reset(wsPingInterval)
   336  
   337  		case <-pingTimer.C:
   338  			wc.jsonCodec.encMu.Lock()
   339  			wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout))
   340  			wc.conn.WriteMessage(websocket.PingMessage, nil)
   341  			wc.conn.SetReadDeadline(time.Now().Add(wsPongTimeout))
   342  			wc.jsonCodec.encMu.Unlock()
   343  			pingTimer.Reset(wsPingInterval)
   344  
   345  		case <-wc.pongReceived:
   346  			wc.conn.SetReadDeadline(time.Time{})
   347  		}
   348  	}
   349  }