websocket.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. wsMessageSizeLimit = 15 * 1024 * 1024
  37. )
  38. var wsBufferPool = new(sync.Pool)
  39. // WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
  40. //
  41. // allowedOrigins should be a comma-separated list of allowed origin URLs.
  42. // To allow connections with any origin, pass "*".
  43. func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler {
  44. var upgrader = websocket.Upgrader{
  45. ReadBufferSize: wsReadBuffer,
  46. WriteBufferSize: wsWriteBuffer,
  47. WriteBufferPool: wsBufferPool,
  48. CheckOrigin: wsHandshakeValidator(allowedOrigins),
  49. }
  50. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  51. conn, err := upgrader.Upgrade(w, r, nil)
  52. if err != nil {
  53. log.Debug("WebSocket upgrade failed", "err", err)
  54. return
  55. }
  56. codec := newWebsocketCodec(conn)
  57. s.ServeCodec(codec, 0)
  58. })
  59. }
  60. // wsHandshakeValidator returns a handler that verifies the origin during the
  61. // websocket upgrade process. When a '*' is specified as an allowed origins all
  62. // connections are accepted.
  63. func wsHandshakeValidator(allowedOrigins []string) func(*http.Request) bool {
  64. origins := mapset.NewSet()
  65. allowAllOrigins := false
  66. for _, origin := range allowedOrigins {
  67. if origin == "*" {
  68. allowAllOrigins = true
  69. }
  70. if origin != "" {
  71. origins.Add(origin)
  72. }
  73. }
  74. // allow localhost if no allowedOrigins are specified.
  75. if len(origins.ToSlice()) == 0 {
  76. origins.Add("http://localhost")
  77. if hostname, err := os.Hostname(); err == nil {
  78. origins.Add("http://" + hostname)
  79. }
  80. }
  81. log.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v", origins.ToSlice()))
  82. f := func(req *http.Request) bool {
  83. // Skip origin verification if no Origin header is present. The origin check
  84. // is supposed to protect against browser based attacks. Browsers always set
  85. // Origin. Non-browser software can put anything in origin and checking it doesn't
  86. // provide additional security.
  87. if _, ok := req.Header["Origin"]; !ok {
  88. return true
  89. }
  90. // Verify origin against whitelist.
  91. origin := strings.ToLower(req.Header.Get("Origin"))
  92. if allowAllOrigins || originIsAllowed(origins, origin) {
  93. return true
  94. }
  95. log.Warn("Rejected WebSocket connection", "origin", origin)
  96. return false
  97. }
  98. return f
  99. }
  100. type wsHandshakeError struct {
  101. err error
  102. status string
  103. }
  104. func (e wsHandshakeError) Error() string {
  105. s := e.err.Error()
  106. if e.status != "" {
  107. s += " (HTTP status " + e.status + ")"
  108. }
  109. return s
  110. }
  111. func originIsAllowed(allowedOrigins mapset.Set, browserOrigin string) bool {
  112. it := allowedOrigins.Iterator()
  113. for origin := range it.C {
  114. if ruleAllowsOrigin(origin.(string), browserOrigin) {
  115. return true
  116. }
  117. }
  118. return false
  119. }
  120. func ruleAllowsOrigin(allowedOrigin string, browserOrigin string) bool {
  121. var (
  122. allowedScheme, allowedHostname, allowedPort string
  123. browserScheme, browserHostname, browserPort string
  124. err error
  125. )
  126. allowedScheme, allowedHostname, allowedPort, err = parseOriginURL(allowedOrigin)
  127. if err != nil {
  128. log.Warn("Error parsing allowed origin specification", "spec", allowedOrigin, "error", err)
  129. return false
  130. }
  131. browserScheme, browserHostname, browserPort, err = parseOriginURL(browserOrigin)
  132. if err != nil {
  133. log.Warn("Error parsing browser 'Origin' field", "Origin", browserOrigin, "error", err)
  134. return false
  135. }
  136. if allowedScheme != "" && allowedScheme != browserScheme {
  137. return false
  138. }
  139. if allowedHostname != "" && allowedHostname != browserHostname {
  140. return false
  141. }
  142. if allowedPort != "" && allowedPort != browserPort {
  143. return false
  144. }
  145. return true
  146. }
  147. func parseOriginURL(origin string) (string, string, string, error) {
  148. parsedURL, err := url.Parse(strings.ToLower(origin))
  149. if err != nil {
  150. return "", "", "", err
  151. }
  152. var scheme, hostname, port string
  153. if strings.Contains(origin, "://") {
  154. scheme = parsedURL.Scheme
  155. hostname = parsedURL.Hostname()
  156. port = parsedURL.Port()
  157. } else {
  158. scheme = ""
  159. hostname = parsedURL.Scheme
  160. port = parsedURL.Opaque
  161. if hostname == "" {
  162. hostname = origin
  163. }
  164. }
  165. return scheme, hostname, port, nil
  166. }
  167. // DialWebsocketWithDialer creates a new RPC client that communicates with a JSON-RPC server
  168. // that is listening on the given endpoint using the provided dialer.
  169. func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error) {
  170. endpoint, header, err := wsClientHeaders(endpoint, origin)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return newClient(ctx, func(ctx context.Context) (ServerCodec, error) {
  175. conn, resp, err := dialer.DialContext(ctx, endpoint, header)
  176. if err != nil {
  177. hErr := wsHandshakeError{err: err}
  178. if resp != nil {
  179. hErr.status = resp.Status
  180. }
  181. return nil, hErr
  182. }
  183. return newWebsocketCodec(conn), nil
  184. })
  185. }
  186. // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server
  187. // that is listening on the given endpoint.
  188. //
  189. // The context is used for the initial connection establishment. It does not
  190. // affect subsequent interactions with the client.
  191. func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) {
  192. dialer := websocket.Dialer{
  193. ReadBufferSize: wsReadBuffer,
  194. WriteBufferSize: wsWriteBuffer,
  195. WriteBufferPool: wsBufferPool,
  196. }
  197. return DialWebsocketWithDialer(ctx, endpoint, origin, dialer)
  198. }
  199. func wsClientHeaders(endpoint, origin string) (string, http.Header, error) {
  200. endpointURL, err := url.Parse(endpoint)
  201. if err != nil {
  202. return endpoint, nil, err
  203. }
  204. header := make(http.Header)
  205. if origin != "" {
  206. header.Add("origin", origin)
  207. }
  208. if endpointURL.User != nil {
  209. b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String()))
  210. header.Add("authorization", "Basic "+b64auth)
  211. endpointURL.User = nil
  212. }
  213. return endpointURL.String(), header, nil
  214. }
  215. type websocketCodec struct {
  216. *jsonCodec
  217. conn *websocket.Conn
  218. wg sync.WaitGroup
  219. pingReset chan struct{}
  220. }
  221. func newWebsocketCodec(conn *websocket.Conn) ServerCodec {
  222. conn.SetReadLimit(wsMessageSizeLimit)
  223. wc := &websocketCodec{
  224. jsonCodec: NewFuncCodec(conn, conn.WriteJSON, conn.ReadJSON).(*jsonCodec),
  225. conn: conn,
  226. pingReset: make(chan struct{}, 1),
  227. }
  228. wc.wg.Add(1)
  229. go wc.pingLoop()
  230. return wc
  231. }
  232. func (wc *websocketCodec) close() {
  233. wc.jsonCodec.close()
  234. wc.wg.Wait()
  235. }
  236. func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}) error {
  237. err := wc.jsonCodec.writeJSON(ctx, v)
  238. if err == nil {
  239. // Notify pingLoop to delay the next idle ping.
  240. select {
  241. case wc.pingReset <- struct{}{}:
  242. default:
  243. }
  244. }
  245. return err
  246. }
  247. // pingLoop sends periodic ping frames when the connection is idle.
  248. func (wc *websocketCodec) pingLoop() {
  249. var timer = time.NewTimer(wsPingInterval)
  250. defer wc.wg.Done()
  251. defer timer.Stop()
  252. for {
  253. select {
  254. case <-wc.closed():
  255. return
  256. case <-wc.pingReset:
  257. if !timer.Stop() {
  258. <-timer.C
  259. }
  260. timer.Reset(wsPingInterval)
  261. case <-timer.C:
  262. wc.jsonCodec.encMu.Lock()
  263. wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout))
  264. wc.conn.WriteMessage(websocket.PingMessage, nil)
  265. wc.jsonCodec.encMu.Unlock()
  266. timer.Reset(wsPingInterval)
  267. }
  268. }
  269. }