github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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/http"
    29  	"net/url"
    30  	"sync"
    31  	"time"
    32  
    33  	"github.com/kisexp/xdchain/log"
    34  )
    35  
    36  const (
    37  	maxRequestContentLength = 1024 * 1024 * 5
    38  	contentType             = "application/json"
    39  )
    40  
    41  // https://www.jsonrpc.org/historical/json-rpc-over-http.html#id13
    42  var acceptedContentTypes = []string{contentType, "application/json-rpc", "application/jsonrequest"}
    43  
    44  type httpConn struct {
    45  	client    *http.Client
    46  	url       string
    47  	closeOnce sync.Once
    48  	closeCh   chan interface{}
    49  	mu        sync.Mutex // protects headers
    50  	headers   http.Header
    51  
    52  	// Quorum
    53  	// To return value being populated in Authorization request header
    54  	credentialsProvider HttpCredentialsProviderFunc
    55  	// psiProvider returns a value being populated in HttpPrivateStateIdentifierHeader
    56  	psiProvider PSIProviderFunc
    57  }
    58  
    59  // httpConn is treated specially by Client.
    60  func (hc *httpConn) writeJSON(context.Context, interface{}) error {
    61  	panic("writeJSON called on httpConn")
    62  }
    63  
    64  func (hc *httpConn) remoteAddr() string {
    65  	return hc.url
    66  }
    67  
    68  func (hc *httpConn) readBatch() ([]*jsonrpcMessage, bool, error) {
    69  	<-hc.closeCh
    70  	return nil, false, io.EOF
    71  }
    72  
    73  func (hc *httpConn) close() {
    74  	hc.closeOnce.Do(func() { close(hc.closeCh) })
    75  }
    76  
    77  func (hc *httpConn) closed() <-chan interface{} {
    78  	return hc.closeCh
    79  }
    80  
    81  func (hc *httpConn) Configure(_ SecurityContext) {
    82  	// Client doesn't need to implement this
    83  }
    84  
    85  func (hc *httpConn) Resolve() SecurityContext {
    86  	// Client doesn't need to implement this
    87  	return context.Background()
    88  }
    89  
    90  // HTTPTimeouts represents the configuration params for the HTTP RPC server.
    91  type HTTPTimeouts struct {
    92  	// ReadTimeout is the maximum duration for reading the entire
    93  	// request, including the body.
    94  	//
    95  	// Because ReadTimeout does not let Handlers make per-request
    96  	// decisions on each request body's acceptable deadline or
    97  	// upload rate, most users will prefer to use
    98  	// ReadHeaderTimeout. It is valid to use them both.
    99  	ReadTimeout time.Duration
   100  
   101  	// WriteTimeout is the maximum duration before timing out
   102  	// writes of the response. It is reset whenever a new
   103  	// request's header is read. Like ReadTimeout, it does not
   104  	// let Handlers make decisions on a per-request basis.
   105  	WriteTimeout time.Duration
   106  
   107  	// IdleTimeout is the maximum amount of time to wait for the
   108  	// next request when keep-alives are enabled. If IdleTimeout
   109  	// is zero, the value of ReadTimeout is used. If both are
   110  	// zero, ReadHeaderTimeout is used.
   111  	IdleTimeout time.Duration
   112  }
   113  
   114  // DefaultHTTPTimeouts represents the default timeout values used if further
   115  // configuration is not provided.
   116  var DefaultHTTPTimeouts = HTTPTimeouts{
   117  	ReadTimeout:  30 * time.Second,
   118  	WriteTimeout: 30 * time.Second,
   119  	IdleTimeout:  120 * time.Second,
   120  }
   121  
   122  // DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP
   123  // using the provided HTTP Client.
   124  func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error) {
   125  	// Sanity check URL so we don't end up with a client that will fail every request.
   126  	_, err := url.Parse(endpoint)
   127  	if err != nil {
   128  		return nil, err
   129  	}
   130  
   131  	headers := make(http.Header, 2)
   132  	headers.Set("accept", contentType)
   133  	headers.Set("content-type", contentType)
   134  	initctx := resolvePSIProvider(context.Background(), endpoint)
   135  
   136  	return newClient(initctx, func(context.Context) (ServerCodec, error) {
   137  		hc := &httpConn{
   138  			client:  client,
   139  			headers: headers,
   140  			url:     endpoint,
   141  			closeCh: make(chan interface{}),
   142  		}
   143  		return hc, nil
   144  	})
   145  }
   146  
   147  // DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
   148  func DialHTTP(endpoint string) (*Client, error) {
   149  	return DialHTTPWithClient(endpoint, new(http.Client))
   150  }
   151  
   152  func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
   153  	hc := c.writeConn.(*httpConn)
   154  	respBody, err := hc.doRequest(ctx, msg)
   155  	if respBody != nil {
   156  		defer respBody.Close()
   157  	}
   158  
   159  	if err != nil {
   160  		if respBody != nil {
   161  			buf := new(bytes.Buffer)
   162  			if _, err2 := buf.ReadFrom(respBody); err2 == nil {
   163  				return fmt.Errorf("%v: %v", err, buf.String())
   164  			}
   165  		}
   166  		return err
   167  	}
   168  	var respmsg jsonrpcMessage
   169  	if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
   170  		return err
   171  	}
   172  	op.resp <- &respmsg
   173  	return nil
   174  }
   175  
   176  func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
   177  	hc := c.writeConn.(*httpConn)
   178  	respBody, err := hc.doRequest(ctx, msgs)
   179  	if err != nil {
   180  		return err
   181  	}
   182  	defer respBody.Close()
   183  	var respmsgs []jsonrpcMessage
   184  	if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
   185  		return err
   186  	}
   187  	for i := 0; i < len(respmsgs); i++ {
   188  		op.resp <- &respmsgs[i]
   189  	}
   190  	return nil
   191  }
   192  
   193  // Quorum
   194  //
   195  // Populate Authorization request header with value from credentials provider
   196  // Ignore if provider is unable to return the value
   197  func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
   198  	body, err := json.Marshal(msg)
   199  	if err != nil {
   200  		return nil, err
   201  	}
   202  	req, err := http.NewRequestWithContext(ctx, "POST", hc.url, ioutil.NopCloser(bytes.NewReader(body)))
   203  	if err != nil {
   204  		return nil, err
   205  	}
   206  	req.ContentLength = int64(len(body))
   207  
   208  	// set headers
   209  	hc.mu.Lock()
   210  	req.Header = hc.headers.Clone()
   211  
   212  	// Quorum
   213  	// do request
   214  	if hc.credentialsProvider != nil {
   215  		if token, err := hc.credentialsProvider(ctx); err != nil {
   216  			log.Warn("unable to obtain http credentials from provider", "err", err)
   217  		} else {
   218  			req.Header.Set(HttpAuthorizationHeader, token)
   219  		}
   220  	}
   221  	if hc.psiProvider != nil {
   222  		if psi, err := hc.psiProvider(ctx); err != nil {
   223  			log.Warn("unable to obtain PSI from provider", "err", err)
   224  		} else {
   225  			req.Header.Set(HttpPrivateStateIdentifierHeader, psi.String())
   226  		}
   227  	}
   228  	// End Quorum
   229  
   230  	hc.mu.Unlock()
   231  
   232  	resp, err := hc.client.Do(req)
   233  	if err != nil {
   234  		return nil, err
   235  	}
   236  	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
   237  		return resp.Body, errors.New(resp.Status)
   238  	}
   239  	return resp.Body, nil
   240  }
   241  
   242  // httpServerConn turns a HTTP connection into a Conn.
   243  type httpServerConn struct {
   244  	io.Reader
   245  	io.Writer
   246  	r *http.Request
   247  }
   248  
   249  func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec {
   250  	body := io.LimitReader(r.Body, maxRequestContentLength)
   251  	conn := &httpServerConn{Reader: body, Writer: w, r: r}
   252  	return NewCodec(conn)
   253  }
   254  
   255  // Close does nothing and always returns nil.
   256  func (t *httpServerConn) Close() error { return nil }
   257  
   258  // RemoteAddr returns the peer address of the underlying connection.
   259  func (t *httpServerConn) RemoteAddr() string {
   260  	return t.r.RemoteAddr
   261  }
   262  
   263  // SetWriteDeadline does nothing and always returns nil.
   264  func (t *httpServerConn) SetWriteDeadline(time.Time) error { return nil }
   265  
   266  // ServeHTTP serves JSON-RPC requests over HTTP.
   267  func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   268  	// Permit dumb empty requests for remote health-checks (AWS)
   269  	if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
   270  		w.WriteHeader(http.StatusOK)
   271  		return
   272  	}
   273  	if code, err := validateRequest(r); err != nil {
   274  		http.Error(w, err.Error(), code)
   275  		return
   276  	}
   277  	// All checks passed, create a codec that reads directly from the request body
   278  	// until EOF, writes the response to w, and orders the server to process a
   279  	// single request.
   280  	ctx := r.Context()
   281  	ctx = context.WithValue(ctx, "remote", r.RemoteAddr)
   282  	ctx = context.WithValue(ctx, "scheme", r.Proto)
   283  	ctx = context.WithValue(ctx, "local", r.Host)
   284  	if ua := r.Header.Get("User-Agent"); ua != "" {
   285  		ctx = context.WithValue(ctx, "User-Agent", ua)
   286  	}
   287  	if origin := r.Header.Get("Origin"); origin != "" {
   288  		ctx = context.WithValue(ctx, "Origin", origin)
   289  	}
   290  	w.Header().Set("content-type", contentType)
   291  	codec := newHTTPServerConn(r, w)
   292  	defer codec.close()
   293  	s.authenticateHttpRequest(r, codec)
   294  	s.serveSingleRequest(ctx, codec)
   295  }
   296  
   297  // validateRequest returns a non-zero response code and error message if the
   298  // request is invalid.
   299  func validateRequest(r *http.Request) (int, error) {
   300  	if r.Method == http.MethodPut || r.Method == http.MethodDelete {
   301  		return http.StatusMethodNotAllowed, errors.New("method not allowed")
   302  	}
   303  	if r.ContentLength > maxRequestContentLength {
   304  		err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxRequestContentLength)
   305  		return http.StatusRequestEntityTooLarge, err
   306  	}
   307  	// Allow OPTIONS (regardless of content-type)
   308  	if r.Method == http.MethodOptions {
   309  		return 0, nil
   310  	}
   311  	// Check content-type
   312  	if mt, _, err := mime.ParseMediaType(r.Header.Get("content-type")); err == nil {
   313  		for _, accepted := range acceptedContentTypes {
   314  			if accepted == mt {
   315  				return 0, nil
   316  			}
   317  		}
   318  	}
   319  	// Invalid content-type
   320  	err := fmt.Errorf("invalid content type, only %s is supported", contentType)
   321  	return http.StatusUnsupportedMediaType, err
   322  }