github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+incompatible/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  	"fmt"
    24  	"io"
    25  	"io/ioutil"
    26  	"net"
    27  	"net/http"
    28  	"sync"
    29  	"time"
    30  
    31  	"github.com/rs/cors"
    32  )
    33  
    34  const (
    35  	maxHTTPRequestContentLength = 1024 * 128
    36  )
    37  
    38  var nullAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:0")
    39  
    40  type httpConn struct {
    41  	client    *http.Client
    42  	req       *http.Request
    43  	closeOnce sync.Once
    44  	closed    chan struct{}
    45  }
    46  
    47  // httpConn is treated specially by Client.
    48  func (hc *httpConn) LocalAddr() net.Addr              { return nullAddr }
    49  func (hc *httpConn) RemoteAddr() net.Addr             { return nullAddr }
    50  func (hc *httpConn) SetReadDeadline(time.Time) error  { return nil }
    51  func (hc *httpConn) SetWriteDeadline(time.Time) error { return nil }
    52  func (hc *httpConn) SetDeadline(time.Time) error      { return nil }
    53  func (hc *httpConn) Write([]byte) (int, error)        { panic("Write called") }
    54  
    55  func (hc *httpConn) Read(b []byte) (int, error) {
    56  	<-hc.closed
    57  	return 0, io.EOF
    58  }
    59  
    60  func (hc *httpConn) Close() error {
    61  	hc.closeOnce.Do(func() { close(hc.closed) })
    62  	return nil
    63  }
    64  
    65  // DialHTTPWithClient creates a new RPC clients that connection to an RPC server over HTTP
    66  // using the provided HTTP Client.
    67  func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error) {
    68  	req, err := http.NewRequest(http.MethodPost, endpoint, nil)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	req.Header.Set("Content-Type", "application/json")
    73  	req.Header.Set("Accept", "application/json")
    74  
    75  	initctx := context.Background()
    76  	return newClient(initctx, func(context.Context) (net.Conn, error) {
    77  		return &httpConn{client: client, req: req, closed: make(chan struct{})}, nil
    78  	})
    79  }
    80  
    81  // DialHTTP creates a new RPC clients that connection to an RPC server over HTTP.
    82  func DialHTTP(endpoint string) (*Client, error) {
    83  	return DialHTTPWithClient(endpoint, new(http.Client))
    84  }
    85  
    86  func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
    87  	hc := c.writeConn.(*httpConn)
    88  	respBody, err := hc.doRequest(ctx, msg)
    89  	if err != nil {
    90  		return err
    91  	}
    92  	defer respBody.Close()
    93  	var respmsg jsonrpcMessage
    94  	if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
    95  		return err
    96  	}
    97  	op.resp <- &respmsg
    98  	return nil
    99  }
   100  
   101  func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
   102  	hc := c.writeConn.(*httpConn)
   103  	respBody, err := hc.doRequest(ctx, msgs)
   104  	if err != nil {
   105  		return err
   106  	}
   107  	defer respBody.Close()
   108  	var respmsgs []jsonrpcMessage
   109  	if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
   110  		return err
   111  	}
   112  	for i := 0; i < len(respmsgs); i++ {
   113  		op.resp <- &respmsgs[i]
   114  	}
   115  	return nil
   116  }
   117  
   118  func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) {
   119  	body, err := json.Marshal(msg)
   120  	if err != nil {
   121  		return nil, err
   122  	}
   123  	req := hc.req.WithContext(ctx)
   124  	req.Body = ioutil.NopCloser(bytes.NewReader(body))
   125  	req.ContentLength = int64(len(body))
   126  
   127  	resp, err := hc.client.Do(req)
   128  	if err != nil {
   129  		return nil, err
   130  	}
   131  	return resp.Body, nil
   132  }
   133  
   134  // httpReadWriteNopCloser wraps a io.Reader and io.Writer with a NOP Close method.
   135  type httpReadWriteNopCloser struct {
   136  	io.Reader
   137  	io.Writer
   138  }
   139  
   140  // Close does nothing and returns always nil
   141  func (t *httpReadWriteNopCloser) Close() error {
   142  	return nil
   143  }
   144  
   145  // NewHTTPServer creates a new HTTP RPC server around an API provider.
   146  //
   147  // Deprecated: Server implements http.Handler
   148  func NewHTTPServer(cors []string, srv *Server) *http.Server {
   149  	return &http.Server{Handler: newCorsHandler(srv, cors)}
   150  }
   151  
   152  // ServeHTTP serves JSON-RPC requests over HTTP.
   153  func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   154  	if r.ContentLength > maxHTTPRequestContentLength {
   155  		http.Error(w,
   156  			fmt.Sprintf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength),
   157  			http.StatusRequestEntityTooLarge)
   158  		return
   159  	}
   160  	w.Header().Set("content-type", "application/json")
   161  
   162  	// create a codec that reads direct from the request body until
   163  	// EOF and writes the response to w and order the server to process
   164  	// a single request.
   165  	codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
   166  	defer codec.Close()
   167  	srv.ServeSingleRequest(codec, OptionMethodInvocation)
   168  }
   169  
   170  func newCorsHandler(srv *Server, allowedOrigins []string) http.Handler {
   171  	// disable CORS support if user has not specified a custom CORS configuration
   172  	if len(allowedOrigins) == 0 {
   173  		return srv
   174  	}
   175  
   176  	c := cors.New(cors.Options{
   177  		AllowedOrigins: allowedOrigins,
   178  		AllowedMethods: []string{"POST", "GET"},
   179  		MaxAge:         600,
   180  		AllowedHeaders: []string{"*"},
   181  	})
   182  	return c.Handler(srv)
   183  }