github.com/cuiweixie/go-ethereum@v1.8.2-0.20180303084001-66cd41af1e38/rpc/http.go (about)

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