websocket.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "encoding/base64"
  20. "fmt"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "strings"
  25. "sync"
  26. "time"
  27. mapset "github.com/deckarep/golang-set"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/gorilla/websocket"
  30. )
  31. const (
  32. wsReadBuffer = 1024
  33. wsWriteBuffer = 1024
  34. wsPingInterval = 60 * time.Second
  35. wsPingWriteTimeout = 5 * time.Second
  36. )
  37. var wsBufferPool = new(sync.Pool)
  38. // WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
  39. //
  40. // allowedOrigins should be a comma-separated list of allowed origin URLs.
  41. // To allow connections with any origin, pass "*".
  42. func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler {
  43. var upgrader = websocket.Upgrader{
  44. ReadBufferSize: wsReadBuffer,
  45. WriteBufferSize: wsWriteBuffer,
  46. WriteBufferPool: wsBufferPool,
  47. CheckOrigin: wsHandshakeValidator(allowedOrigins),
  48. }
  49. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  50. conn, err := upgrader.Upgrade(w, r, nil)
  51. if err != nil {
  52. log.Debug("WebSocket upgrade failed", "err", err)
  53. return
  54. }
  55. codec := newWebsocketCodec(conn)
  56. s.ServeCodec(codec, 0)
  57. })
  58. }
  59. // wsHandshakeValidator returns a handler that verifies the origin during the
  60. // websocket upgrade process. When a '*' is specified as an allowed origins all
  61. // connections are accepted.
  62. func wsHandshakeValidator(allowedOrigins []string) func(*http.Request) bool {
  63. origins := mapset.NewSet()
  64. allowAllOrigins := false
  65. for _, origin := range allowedOrigins {
  66. if origin == "*" {
  67. allowAllOrigins = true
  68. }
  69. if origin != "" {
  70. origins.Add(strings.ToLower(origin))
  71. }
  72. }
  73. // allow localhost if no allowedOrigins are specified.
  74. if len(origins.ToSlice()) == 0 {
  75. origins.Add("http://localhost")
  76. if hostname, err := os.Hostname(); err == nil {
  77. origins.Add("http://" + strings.ToLower(hostname))
  78. }
  79. }
  80. log.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v", origins.ToSlice()))
  81. f := func(req *http.Request) bool {
  82. // Skip origin verification if no Origin header is present. The origin check
  83. // is supposed to protect against browser based attacks. Browsers always set
  84. // Origin. Non-browser software can put anything in origin and checking it doesn't
  85. // provide additional security.
  86. if _, ok := req.Header["Origin"]; !ok {
  87. return true
  88. }
  89. // Verify origin against whitelist.
  90. origin := strings.ToLower(req.Header.Get("Origin"))
  91. if allowAllOrigins || origins.Contains(origin) {
  92. return true
  93. }
  94. log.Warn("Rejected WebSocket connection", "origin", origin)
  95. return false
  96. }
  97. return f
  98. }
  99. type wsHandshakeError struct {
  100. err error
  101. status string
  102. }
  103. func (e wsHandshakeError) Error() string {
  104. s := e.err.Error()
  105. if e.status != "" {
  106. s += " (HTTP status " + e.status + ")"
  107. }
  108. return s
  109. }
  110. // DialWebsocketWithDialer creates a new RPC client that communicates with a JSON-RPC server
  111. // that is listening on the given endpoint using the provided dialer.
  112. func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error) {
  113. endpoint, header, err := wsClientHeaders(endpoint, origin)
  114. if err != nil {
  115. return nil, err
  116. }
  117. return newClient(ctx, func(ctx context.Context) (ServerCodec, error) {
  118. conn, resp, err := dialer.DialContext(ctx, endpoint, header)
  119. if err != nil {
  120. hErr := wsHandshakeError{err: err}
  121. if resp != nil {
  122. hErr.status = resp.Status
  123. }
  124. return nil, hErr
  125. }
  126. return newWebsocketCodec(conn), nil
  127. })
  128. }
  129. // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server
  130. // that is listening on the given endpoint.
  131. //
  132. // The context is used for the initial connection establishment. It does not
  133. // affect subsequent interactions with the client.
  134. func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) {
  135. dialer := websocket.Dialer{
  136. ReadBufferSize: wsReadBuffer,
  137. WriteBufferSize: wsWriteBuffer,
  138. WriteBufferPool: wsBufferPool,
  139. }
  140. return DialWebsocketWithDialer(ctx, endpoint, origin, dialer)
  141. }
  142. func wsClientHeaders(endpoint, origin string) (string, http.Header, error) {
  143. endpointURL, err := url.Parse(endpoint)
  144. if err != nil {
  145. return endpoint, nil, err
  146. }
  147. header := make(http.Header)
  148. if origin != "" {
  149. header.Add("origin", origin)
  150. }
  151. if endpointURL.User != nil {
  152. b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String()))
  153. header.Add("authorization", "Basic "+b64auth)
  154. endpointURL.User = nil
  155. }
  156. return endpointURL.String(), header, nil
  157. }
  158. type websocketCodec struct {
  159. *jsonCodec
  160. conn *websocket.Conn
  161. wg sync.WaitGroup
  162. pingReset chan struct{}
  163. }
  164. func newWebsocketCodec(conn *websocket.Conn) ServerCodec {
  165. conn.SetReadLimit(maxRequestContentLength)
  166. wc := &websocketCodec{
  167. jsonCodec: NewFuncCodec(conn, conn.WriteJSON, conn.ReadJSON).(*jsonCodec),
  168. conn: conn,
  169. pingReset: make(chan struct{}, 1),
  170. }
  171. wc.wg.Add(1)
  172. go wc.pingLoop()
  173. return wc
  174. }
  175. func (wc *websocketCodec) close() {
  176. wc.jsonCodec.close()
  177. wc.wg.Wait()
  178. }
  179. func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}) error {
  180. err := wc.jsonCodec.writeJSON(ctx, v)
  181. if err == nil {
  182. // Notify pingLoop to delay the next idle ping.
  183. select {
  184. case wc.pingReset <- struct{}{}:
  185. default:
  186. }
  187. }
  188. return err
  189. }
  190. // pingLoop sends periodic ping frames when the connection is idle.
  191. func (wc *websocketCodec) pingLoop() {
  192. var timer = time.NewTimer(wsPingInterval)
  193. defer wc.wg.Done()
  194. defer timer.Stop()
  195. for {
  196. select {
  197. case <-wc.closed():
  198. return
  199. case <-wc.pingReset:
  200. if !timer.Stop() {
  201. <-timer.C
  202. }
  203. timer.Reset(wsPingInterval)
  204. case <-timer.C:
  205. wc.jsonCodec.encMu.Lock()
  206. wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout))
  207. wc.conn.WriteMessage(websocket.PingMessage, nil)
  208. wc.jsonCodec.encMu.Unlock()
  209. timer.Reset(wsPingInterval)
  210. }
  211. }
  212. }