github.com/aerth/aquachain@v1.4.1/rpc/http.go (about)

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