websocket.go 7.2 KB

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