websocket.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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(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://" + 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 || originIsAllowed(origins, 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. func originIsAllowed(allowedOrigins mapset.Set, browserOrigin string) bool {
  111. it := allowedOrigins.Iterator()
  112. for origin := range it.C {
  113. if ruleAllowsOrigin(origin.(string), browserOrigin) {
  114. return true
  115. }
  116. }
  117. return false
  118. }
  119. func ruleAllowsOrigin(allowedOrigin string, browserOrigin string) bool {
  120. var (
  121. allowedScheme, allowedHostname, allowedPort string
  122. browserScheme, browserHostname, browserPort string
  123. err error
  124. )
  125. allowedScheme, allowedHostname, allowedPort, err = parseOriginURL(allowedOrigin)
  126. if err != nil {
  127. log.Warn("Error parsing allowed origin specification", "spec", allowedOrigin, "error", err)
  128. return false
  129. }
  130. browserScheme, browserHostname, browserPort, err = parseOriginURL(browserOrigin)
  131. if err != nil {
  132. log.Warn("Error parsing browser 'Origin' field", "Origin", browserOrigin, "error", err)
  133. return false
  134. }
  135. if allowedScheme != "" && allowedScheme != browserScheme {
  136. return false
  137. }
  138. if allowedHostname != "" && allowedHostname != browserHostname {
  139. return false
  140. }
  141. if allowedPort != "" && allowedPort != browserPort {
  142. return false
  143. }
  144. return true
  145. }
  146. func parseOriginURL(origin string) (string, string, string, error) {
  147. parsedURL, err := url.Parse(strings.ToLower(origin))
  148. if err != nil {
  149. return "", "", "", err
  150. }
  151. var scheme, hostname, port string
  152. if strings.Contains(origin, "://") {
  153. scheme = parsedURL.Scheme
  154. hostname = parsedURL.Hostname()
  155. port = parsedURL.Port()
  156. } else {
  157. scheme = ""
  158. hostname = parsedURL.Scheme
  159. port = parsedURL.Opaque
  160. if hostname == "" {
  161. hostname = origin
  162. }
  163. }
  164. return scheme, hostname, port, nil
  165. }
  166. // DialWebsocketWithDialer creates a new RPC client that communicates with a JSON-RPC server
  167. // that is listening on the given endpoint using the provided dialer.
  168. func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error) {
  169. endpoint, header, err := wsClientHeaders(endpoint, origin)
  170. if err != nil {
  171. return nil, err
  172. }
  173. return newClient(ctx, func(ctx context.Context) (ServerCodec, error) {
  174. conn, resp, err := dialer.DialContext(ctx, endpoint, header)
  175. if err != nil {
  176. hErr := wsHandshakeError{err: err}
  177. if resp != nil {
  178. hErr.status = resp.Status
  179. }
  180. return nil, hErr
  181. }
  182. return newWebsocketCodec(conn), nil
  183. })
  184. }
  185. // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server
  186. // that is listening on the given endpoint.
  187. //
  188. // The context is used for the initial connection establishment. It does not
  189. // affect subsequent interactions with the client.
  190. func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) {
  191. dialer := websocket.Dialer{
  192. ReadBufferSize: wsReadBuffer,
  193. WriteBufferSize: wsWriteBuffer,
  194. WriteBufferPool: wsBufferPool,
  195. }
  196. return DialWebsocketWithDialer(ctx, endpoint, origin, dialer)
  197. }
  198. func wsClientHeaders(endpoint, origin string) (string, http.Header, error) {
  199. endpointURL, err := url.Parse(endpoint)
  200. if err != nil {
  201. return endpoint, nil, err
  202. }
  203. header := make(http.Header)
  204. if origin != "" {
  205. header.Add("origin", origin)
  206. }
  207. if endpointURL.User != nil {
  208. b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String()))
  209. header.Add("authorization", "Basic "+b64auth)
  210. endpointURL.User = nil
  211. }
  212. return endpointURL.String(), header, nil
  213. }
  214. type websocketCodec struct {
  215. *jsonCodec
  216. conn *websocket.Conn
  217. wg sync.WaitGroup
  218. pingReset chan struct{}
  219. }
  220. func newWebsocketCodec(conn *websocket.Conn) ServerCodec {
  221. conn.SetReadLimit(maxRequestContentLength)
  222. wc := &websocketCodec{
  223. jsonCodec: NewFuncCodec(conn, conn.WriteJSON, conn.ReadJSON).(*jsonCodec),
  224. conn: conn,
  225. pingReset: make(chan struct{}, 1),
  226. }
  227. wc.wg.Add(1)
  228. go wc.pingLoop()
  229. return wc
  230. }
  231. func (wc *websocketCodec) close() {
  232. wc.jsonCodec.close()
  233. wc.wg.Wait()
  234. }
  235. func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}) error {
  236. err := wc.jsonCodec.writeJSON(ctx, v)
  237. if err == nil {
  238. // Notify pingLoop to delay the next idle ping.
  239. select {
  240. case wc.pingReset <- struct{}{}:
  241. default:
  242. }
  243. }
  244. return err
  245. }
  246. // pingLoop sends periodic ping frames when the connection is idle.
  247. func (wc *websocketCodec) pingLoop() {
  248. var timer = time.NewTimer(wsPingInterval)
  249. defer wc.wg.Done()
  250. defer timer.Stop()
  251. for {
  252. select {
  253. case <-wc.closed():
  254. return
  255. case <-wc.pingReset:
  256. if !timer.Stop() {
  257. <-timer.C
  258. }
  259. timer.Reset(wsPingInterval)
  260. case <-timer.C:
  261. wc.jsonCodec.encMu.Lock()
  262. wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout))
  263. wc.conn.WriteMessage(websocket.PingMessage, nil)
  264. wc.jsonCodec.encMu.Unlock()
  265. timer.Reset(wsPingInterval)
  266. }
  267. }
  268. }