websocket.go 5.9 KB

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