github.com/gochain-io/gochain@v2.2.26+incompatible/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 "bytes" 21 "context" 22 "crypto/tls" 23 "encoding/base64" 24 "encoding/json" 25 "fmt" 26 "net" 27 "net/http" 28 "net/url" 29 "os" 30 "strings" 31 "time" 32 33 "github.com/gochain-io/gochain/log" 34 "golang.org/x/net/websocket" 35 ) 36 37 // websocketJSONCodec is a custom JSON codec with payload size enforcement and 38 // special number parsing. 39 var websocketJSONCodec = websocket.Codec{ 40 // Marshal is the stock JSON marshaller used by the websocket library too. 41 Marshal: func(v interface{}) ([]byte, byte, error) { 42 msg, err := json.Marshal(v) 43 return msg, websocket.TextFrame, err 44 }, 45 // Unmarshal is a specialized unmarshaller to properly convert numbers. 46 Unmarshal: func(msg []byte, payloadType byte, v interface{}) error { 47 dec := json.NewDecoder(bytes.NewReader(msg)) 48 dec.UseNumber() 49 50 return dec.Decode(v) 51 }, 52 } 53 54 // WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections. 55 // 56 // allowedOrigins should be a comma-separated list of allowed origin URLs. 57 // To allow connections with any origin, pass "*". 58 func (srv *Server) WebsocketHandler(allowedOrigins []string) http.Handler { 59 return websocket.Server{ 60 Handshake: wsHandshakeValidator(allowedOrigins), 61 Handler: func(conn *websocket.Conn) { 62 // Create a custom encode/decode pair to enforce payload size and number encoding 63 conn.MaxPayloadBytes = maxRequestContentLength 64 65 encoder := func(v interface{}) error { 66 return websocketJSONCodec.Send(conn, v) 67 } 68 decoder := func(v interface{}) error { 69 return websocketJSONCodec.Receive(conn, v) 70 } 71 srv.ServeCodec(NewCodec(conn, encoder, decoder), OptionMethodInvocation|OptionSubscriptions) 72 }, 73 } 74 } 75 76 // NewWSServer creates a new websocket RPC server around an API provider. 77 // 78 // Deprecated: use Server.WebsocketHandler 79 func NewWSServer(allowedOrigins []string, srv *Server) *http.Server { 80 return &http.Server{Handler: srv.WebsocketHandler(allowedOrigins)} 81 } 82 83 // wsHandshakeValidator returns a handler that verifies the origin during the 84 // websocket upgrade process. When a '*' is specified as an allowed origins all 85 // connections are accepted. 86 func wsHandshakeValidator(allowedOrigins []string) func(*websocket.Config, *http.Request) error { 87 origins := make(map[string]struct{}) 88 allowAllOrigins := false 89 90 for _, origin := range allowedOrigins { 91 if origin == "*" { 92 allowAllOrigins = true 93 } 94 if origin != "" { 95 origins[strings.ToLower(origin)] = struct{}{} 96 } 97 } 98 99 // allow localhost if no allowedOrigins are specified. 100 if len(origins) == 0 { 101 origins["http://localhost"] = struct{}{} 102 if hostname, err := os.Hostname(); err == nil { 103 origins["http://"+strings.ToLower(hostname)] = struct{}{} 104 } 105 } 106 107 log.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v\n", origins)) 108 109 f := func(cfg *websocket.Config, req *http.Request) error { 110 origin := strings.ToLower(req.Header.Get("Origin")) 111 if allowAllOrigins { 112 return nil 113 } else if _, ok := origins[origin]; ok { 114 return nil 115 } 116 log.Warn(fmt.Sprintf("origin '%s' not allowed on WS-RPC interface\n", origin)) 117 return fmt.Errorf("origin %s not allowed", origin) 118 } 119 120 return f 121 } 122 123 func wsGetConfig(endpoint, origin string) (*websocket.Config, error) { 124 if origin == "" { 125 var err error 126 if origin, err = os.Hostname(); err != nil { 127 return nil, err 128 } 129 if strings.HasPrefix(endpoint, "wss") { 130 origin = "https://" + strings.ToLower(origin) 131 } else { 132 origin = "http://" + strings.ToLower(origin) 133 } 134 } 135 config, err := websocket.NewConfig(endpoint, origin) 136 if err != nil { 137 return nil, err 138 } 139 140 if config.Location.User != nil { 141 b64auth := base64.StdEncoding.EncodeToString([]byte(config.Location.User.String())) 142 config.Header.Add("Authorization", "Basic "+b64auth) 143 config.Location.User = nil 144 } 145 return config, nil 146 } 147 148 // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server 149 // that is listening on the given endpoint. 150 // 151 // The context is used for the initial connection establishment. It does not 152 // affect subsequent interactions with the client. 153 func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) { 154 config, err := wsGetConfig(endpoint, origin) 155 if err != nil { 156 return nil, err 157 } 158 159 return newClient(ctx, func(ctx context.Context) (net.Conn, error) { 160 return wsDialContext(ctx, config) 161 }) 162 } 163 164 func wsDialContext(ctx context.Context, config *websocket.Config) (*websocket.Conn, error) { 165 var conn net.Conn 166 var err error 167 switch config.Location.Scheme { 168 case "ws": 169 conn, err = dialContext(ctx, "tcp", wsDialAddress(config.Location)) 170 case "wss": 171 dialer := contextDialer(ctx) 172 conn, err = tls.DialWithDialer(dialer, "tcp", wsDialAddress(config.Location), config.TlsConfig) 173 default: 174 err = websocket.ErrBadScheme 175 } 176 if err != nil { 177 return nil, err 178 } 179 ws, err := websocket.NewClient(config, conn) 180 if err != nil { 181 if e := conn.Close(); e != nil { 182 log.Error("Cannot close websocket connection on error", "err", err) 183 } 184 return nil, err 185 } 186 return ws, err 187 } 188 189 var wsPortMap = map[string]string{"ws": "80", "wss": "443"} 190 191 func wsDialAddress(location *url.URL) string { 192 if _, ok := wsPortMap[location.Scheme]; ok { 193 if _, _, err := net.SplitHostPort(location.Host); err != nil { 194 return net.JoinHostPort(location.Host, wsPortMap[location.Scheme]) 195 } 196 } 197 return location.Host 198 } 199 200 func dialContext(ctx context.Context, network, addr string) (net.Conn, error) { 201 d := &net.Dialer{KeepAlive: tcpKeepAliveInterval} 202 return d.DialContext(ctx, network, addr) 203 } 204 205 func contextDialer(ctx context.Context) *net.Dialer { 206 dialer := &net.Dialer{Cancel: ctx.Done(), KeepAlive: tcpKeepAliveInterval} 207 if deadline, ok := ctx.Deadline(); ok { 208 dialer.Deadline = deadline 209 } else { 210 dialer.Deadline = time.Now().Add(defaultDialTimeout) 211 } 212 return dialer 213 }