github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/rpc/http.go (about)

     1  // Copyright 2015 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum 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  )
    35  
    36  const (
    37  	contentType                 = "application/json"
    38  	maxHTTPRequestContentLength = 1024 * 128
    39  )
    40  
    41  var nullAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:0")
    42  
    43  type httpConn struct {
    44  	client    *http.Client
    45  	req       *http.Request
    46  	closeOnce sync.Once
    47  	closed    chan struct{}
    48  }
    49  
    50  // httpConn is treated specially by Client.
    51  func (hc *httpConn) LocalAddr() net.Addr              { return nullAddr }
    52  func (hc *httpConn) RemoteAddr() net.Addr             { return nullAddr }
    53  func (hc *httpConn) SetReadDeadline(time.Time) error  { return nil }
    54  func (hc *httpConn) SetWriteDeadline(time.Time) error { return nil }
    55  func (hc *httpConn) SetDeadline(time.Time) error      { return nil }
    56  func (hc *httpConn) Write([]byte) (int, error)        { panic("Write called") }
    57  
    58  func (hc *httpConn) Read(b []byte) (int, error) {
    59  	<-hc.closed
    60  	return 0, io.EOF
    61  }
    62  
    63  func (hc *httpConn) Close() error {
    64  	hc.closeOnce.Do(func() { close(hc.closed) })
    65  	return nil
    66  }
    67  
    68  // DialHTTP creates a new RPC clients that connection to an RPC server over HTTP.
    69  func DialHTTP(endpoint string) (*Client, error) {
    70  	req, err := http.NewRequest(http.MethodPost, endpoint, nil)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	req.Header.Set("Content-Type", contentType)
    75  	req.Header.Set("Accept", contentType)
    76  
    77  	initctx := context.Background()
    78  	return newClient(initctx, func(context.Context) (net.Conn, error) {
    79  		return &httpConn{client: new(http.Client), req: req, closed: make(chan struct{})}, nil
    80  	})
    81  }
    82  
    83  func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error {
    84  	hc := c.writeConn.(*httpConn)
    85  	respBody, err := hc.doRequest(ctx, msg)
    86  	if err != nil {
    87  		return err
    88  	}
    89  	defer respBody.Close()
    90  	var respmsg jsonrpcMessage
    91  	if err := json.NewDecoder(respBody).Decode(&respmsg); err != nil {
    92  		return err
    93  	}
    94  	op.resp <- &respmsg
    95  	return nil
    96  }
    97  
    98  func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonrpcMessage) error {
    99  	hc := c.writeConn.(*httpConn)
   100  	respBody, err := hc.doRequest(ctx, msgs)
   101  	if err != nil {
   102  		return err
   103  	}
   104  	defer respBody.Close()
   105  	var respmsgs []jsonrpcMessage
   106  	if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil {
   107  		return err
   108  	}
   109  	for i := 0; i < len(respmsgs); i++ {
   110  		op.resp <- &respmsgs[i]
   111  	}
   112  	return nil
   113  }
   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  
   124  	resp, err := hc.client.Do(req)
   125  	if err != nil {
   126  		return nil, err
   127  	}
   128  	return resp.Body, nil
   129  }
   130  
   131  // httpReadWriteNopCloser wraps a io.Reader and io.Writer with a NOP Close method.
   132  type httpReadWriteNopCloser struct {
   133  	io.Reader
   134  	io.Writer
   135  }
   136  
   137  // Close does nothing and returns always nil
   138  func (t *httpReadWriteNopCloser) Close() error {
   139  	return nil
   140  }
   141  
   142  // NewHTTPServer creates a new HTTP RPC server around an API provider.
   143  //
   144  // Deprecated: Server implements http.Handler
   145  func NewHTTPServer(cors []string, srv *Server) *http.Server {
   146  	return &http.Server{Handler: newCorsHandler(srv, cors)}
   147  }
   148  
   149  // ServeHTTP serves JSON-RPC requests over HTTP.
   150  func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   151  	// Permit dumb empty requests for remote health-checks (AWS)
   152  	if r.Method == http.MethodGet && r.ContentLength == 0 && r.URL.RawQuery == "" {
   153  		return
   154  	}
   155  	if code, err := validateRequest(r); err != nil {
   156  		http.Error(w, err.Error(), code)
   157  		return
   158  	}
   159  	// All checks passed, create a codec that reads direct from the request body
   160  	// untilEOF and writes the response to w and order the server to process a
   161  	// single request.
   162  	codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
   163  	defer codec.Close()
   164  
   165  	w.Header().Set("content-type", contentType)
   166  	srv.ServeSingleRequest(codec, OptionMethodInvocation)
   167  }
   168  
   169  // validateRequest returns a non-zero response code and error message if the
   170  // request is invalid.
   171  func validateRequest(r *http.Request) (int, error) {
   172  	if r.Method == http.MethodPut || r.Method == http.MethodDelete {
   173  		return http.StatusMethodNotAllowed, errors.New("method not allowed")
   174  	}
   175  	if r.ContentLength > maxHTTPRequestContentLength {
   176  		err := fmt.Errorf("content length too large (%d>%d)", r.ContentLength, maxHTTPRequestContentLength)
   177  		return http.StatusRequestEntityTooLarge, err
   178  	}
   179  	mt, _, err := mime.ParseMediaType(r.Header.Get("content-type"))
   180  	if r.Method != http.MethodOptions && (err != nil || mt != contentType) {
   181  		err := fmt.Errorf("invalid content type, only %s is supported", contentType)
   182  		return http.StatusUnsupportedMediaType, err
   183  	}
   184  	return 0, nil
   185  }
   186  
   187  func newCorsHandler(srv *Server, allowedOrigins []string) http.Handler {
   188  	// disable CORS support if user has not specified a custom CORS configuration
   189  	if len(allowedOrigins) == 0 {
   190  		return srv
   191  	}
   192  
   193  	c := cors.New(cors.Options{
   194  		AllowedOrigins: allowedOrigins,
   195  		AllowedMethods: []string{http.MethodPost, http.MethodGet},
   196  		MaxAge:         600,
   197  		AllowedHeaders: []string{"*"},
   198  	})
   199  	return c.Handler(srv)
   200  }