websocket.go 5.0 KB

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