http.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "mime"
  26. "net"
  27. "net/http"
  28. "strings"
  29. "sync"
  30. "time"
  31. "github.com/rs/cors"
  32. )
  33. const (
  34. contentType = "application/json"
  35. maxRequestContentLength = 1024 * 128
  36. )
  37. var nullAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:0")
  38. type httpConn struct {
  39. client *http.Client
  40. req *http.Request
  41. closeOnce sync.Once
  42. closed chan struct{}
  43. }
  44. // httpConn is treated specially by Client.
  45. func (hc *httpConn) LocalAddr() net.Addr { return nullAddr }
  46. func (hc *httpConn) RemoteAddr() net.Addr { return nullAddr }
  47. func (hc *httpConn) SetReadDeadline(time.Time) error { return nil }
  48. func (hc *httpConn) SetWriteDeadline(time.Time) error { return nil }
  49. func (hc *httpConn) SetDeadline(time.Time) error { return nil }
  50. func (hc *httpConn) Write([]byte) (int, error) { panic("Write called") }
  51. func (hc *httpConn) Read(b []byte) (int, error) {
  52. <-hc.closed
  53. return 0, io.EOF
  54. }
  55. func (hc *httpConn) Close() error {
  56. hc.closeOnce.Do(func() { close(hc.closed) })
  57. return nil
  58. }
  59. // DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP
  60. // using the provided HTTP Client.
  61. func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error) {
  62. req, err := http.NewRequest(http.MethodPost, endpoint, nil)
  63. if err != nil {
  64. return nil, err
  65. }
  66. req.Header.Set("Content-Type", contentType)
  67. req.Header.Set("Accept", contentType)
  68. initctx := context.Background()
  69. return newClient(initctx, func(context.Context) (net.Conn, error) {
  70. return &httpConn{client: client, req: req, closed: make(chan struct{})}, nil
  71. })
  72. }
  73. // DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
  74. func DialHTTP(endpoint string) (*Client, error) {
  75. return DialHTTPWithClient(endpoint, new(http.Client))
  76. }
  77. func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
  78. hc := c.writeConn.(*httpConn)
  79. respBody, err := hc.doRequest(ctx, msg)
  80. if respBody != nil {
  81. defer respBody.Close()
  82. }
  83. if err != nil {
  84. if respBody != nil {
  85. buf := new(bytes.Buffer)
  86. if _, err2 := buf.ReadFrom(respBody); err2 == nil {
  87. return fmt.Errorf("%v %v", err, buf.String())
  88. }
  89. }
  90. return err
  91. }
  92. var respmsg jsonrpcMessage
  93. if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
  94. return err
  95. }
  96. op.resp <- &respmsg
  97. return nil
  98. }
  99. func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
  100. hc := c.writeConn.(*httpConn)
  101. respBody, err := hc.doRequest(ctx, msgs)
  102. if err != nil {
  103. return err
  104. }
  105. defer respBody.Close()
  106. var respmsgs []jsonrpcMessage
  107. if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
  108. return err
  109. }
  110. for i := 0; i < len(respmsgs); i++ {
  111. op.resp <- &respmsgs[i]
  112. }
  113. return nil
  114. }
  115. func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
  116. body, err := json.Marshal(msg)
  117. if err != nil {
  118. return nil, err
  119. }
  120. req := hc.req.WithContext(ctx)
  121. req.Body = ioutil.NopCloser(bytes.NewReader(body))
  122. req.ContentLength = int64(len(body))
  123. resp, err := hc.client.Do(req)
  124. if err != nil {
  125. return nil, err
  126. }
  127. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  128. return resp.Body, errors.New(resp.Status)
  129. }
  130. return resp.Body, nil
  131. }
  132. // httpReadWriteNopCloser wraps a io.Reader and io.Writer with a NOP Close method.
  133. type httpReadWriteNopCloser struct {
  134. io.Reader
  135. io.Writer
  136. }
  137. // Close does nothing and returns always nil
  138. func (t *httpReadWriteNopCloser) Close() error {
  139. return nil
  140. }
  141. // NewHTTPServer creates a new HTTP RPC server around an API provider.
  142. //
  143. // Deprecated: Server implements http.Handler
  144. func NewHTTPServer(cors []string, vhosts []string, srv *Server) *http.Server {
  145. // Wrap the CORS-handler within a host-handler
  146. handler := newCorsHandler(srv, cors)
  147. handler = newVHostHandler(vhosts, handler)
  148. return &http.Server{
  149. Handler: handler,
  150. ReadTimeout: 5 * time.Second,
  151. WriteTimeout: 10 * time.Second,
  152. IdleTimeout: 120 * time.Second,
  153. }
  154. }
  155. // ServeHTTP serves JSON-RPC requests over HTTP.
  156. func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  157. // Permit dumb empty requests for remote health-checks (AWS)
  158. if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
  159. return
  160. }
  161. if code, err := validateRequest(r); err != nil {
  162. http.Error(w, err.Error(), code)
  163. return
  164. }
  165. // All checks passed, create a codec that reads direct from the request body
  166. // untilEOF and writes the response to w and order the server to process a
  167. // single request.
  168. ctx := r.Context()
  169. ctx = context.WithValue(ctx, "remote", r.RemoteAddr)
  170. ctx = context.WithValue(ctx, "scheme", r.Proto)
  171. ctx = context.WithValue(ctx, "local", r.Host)
  172. body := io.LimitReader(r.Body, maxRequestContentLength)
  173. codec := NewJSONCodec(&httpReadWriteNopCloser{body, w})
  174. defer codec.Close()
  175. w.Header().Set("content-type", contentType)
  176. srv.ServeSingleRequest(ctx, codec, OptionMethodInvocation)
  177. }
  178. // validateRequest returns a non-zero response code and error message if the
  179. // request is invalid.
  180. func validateRequest(r *http.Request) (int, error) {
  181. if r.Method == http.MethodPut || r.Method == http.MethodDelete {
  182. return http.StatusMethodNotAllowed, errors.New("method not allowed")
  183. }
  184. if r.ContentLength > maxRequestContentLength {
  185. err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxRequestContentLength)
  186. return http.StatusRequestEntityTooLarge, err
  187. }
  188. mt, _, err := mime.ParseMediaType(r.Header.Get("content-type"))
  189. if r.Method != http.MethodOptions && (err != nil || mt != contentType) {
  190. err := fmt.Errorf("invalid content type, only %s is supported", contentType)
  191. return http.StatusUnsupportedMediaType, err
  192. }
  193. return 0, nil
  194. }
  195. func newCorsHandler(srv *Server, allowedOrigins []string) http.Handler {
  196. // disable CORS support if user has not specified a custom CORS configuration
  197. if len(allowedOrigins) == 0 {
  198. return srv
  199. }
  200. c := cors.New(cors.Options{
  201. AllowedOrigins: allowedOrigins,
  202. AllowedMethods: []string{http.MethodPost, http.MethodGet},
  203. MaxAge: 600,
  204. AllowedHeaders: []string{"*"},
  205. })
  206. return c.Handler(srv)
  207. }
  208. // virtualHostHandler is a handler which validates the Host-header of incoming requests.
  209. // The virtualHostHandler can prevent DNS rebinding attacks, which do not utilize CORS-headers,
  210. // since they do in-domain requests against the RPC api. Instead, we can see on the Host-header
  211. // which domain was used, and validate that against a whitelist.
  212. type virtualHostHandler struct {
  213. vhosts map[string]struct{}
  214. next http.Handler
  215. }
  216. // ServeHTTP serves JSON-RPC requests over HTTP, implements http.Handler
  217. func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  218. // if r.Host is not set, we can continue serving since a browser would set the Host header
  219. if r.Host == "" {
  220. h.next.ServeHTTP(w, r)
  221. return
  222. }
  223. host, _, err := net.SplitHostPort(r.Host)
  224. if err != nil {
  225. // Either invalid (too many colons) or no port specified
  226. host = r.Host
  227. }
  228. if ipAddr := net.ParseIP(host); ipAddr != nil {
  229. // It's an IP address, we can serve that
  230. h.next.ServeHTTP(w, r)
  231. return
  232. }
  233. // Not an ip address, but a hostname. Need to validate
  234. if _, exist := h.vhosts["*"]; exist {
  235. h.next.ServeHTTP(w, r)
  236. return
  237. }
  238. if _, exist := h.vhosts[host]; exist {
  239. h.next.ServeHTTP(w, r)
  240. return
  241. }
  242. http.Error(w, "invalid host specified", http.StatusForbidden)
  243. }
  244. func newVHostHandler(vhosts []string, next http.Handler) http.Handler {
  245. vhostMap := make(map[string]struct{})
  246. for _, allowedHost := range vhosts {
  247. vhostMap[strings.ToLower(allowedHost)] = struct{}{}
  248. }
  249. return &virtualHostHandler{vhostMap, next}
  250. }