github.com/adoriasoft/tendermint@v0.34.0-dev1.0.20200722151356-96d84601a75a/rpc/jsonrpc/server/http_json_handler.go (about)

     1  package server
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"reflect"
    10  	"sort"
    11  
    12  	tmjson "github.com/tendermint/tendermint/libs/json"
    13  	"github.com/tendermint/tendermint/libs/log"
    14  	types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
    15  )
    16  
    17  ///////////////////////////////////////////////////////////////////////////////
    18  // HTTP + JSON handler
    19  ///////////////////////////////////////////////////////////////////////////////
    20  
    21  // jsonrpc calls grab the given method's function info and runs reflect.Call
    22  func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc {
    23  	return func(w http.ResponseWriter, r *http.Request) {
    24  		b, err := ioutil.ReadAll(r.Body)
    25  		if err != nil {
    26  			WriteRPCResponseHTTPError(
    27  				w,
    28  				http.StatusBadRequest,
    29  				types.RPCInvalidRequestError(
    30  					nil,
    31  					fmt.Errorf("error reading request body: %w", err),
    32  				),
    33  			)
    34  			return
    35  		}
    36  
    37  		// if its an empty request (like from a browser), just display a list of
    38  		// functions
    39  		if len(b) == 0 {
    40  			writeListOfEndpoints(w, r, funcMap)
    41  			return
    42  		}
    43  
    44  		// first try to unmarshal the incoming request as an array of RPC requests
    45  		var (
    46  			requests  []types.RPCRequest
    47  			responses []types.RPCResponse
    48  		)
    49  		if err := json.Unmarshal(b, &requests); err != nil {
    50  			// next, try to unmarshal as a single request
    51  			var request types.RPCRequest
    52  			if err := json.Unmarshal(b, &request); err != nil {
    53  				WriteRPCResponseHTTPError(
    54  					w,
    55  					http.StatusInternalServerError,
    56  					types.RPCParseError(
    57  						fmt.Errorf("error unmarshalling request: %w", err),
    58  					),
    59  				)
    60  				return
    61  			}
    62  			requests = []types.RPCRequest{request}
    63  		}
    64  
    65  		for _, request := range requests {
    66  			request := request
    67  
    68  			// A Notification is a Request object without an "id" member.
    69  			// The Server MUST NOT reply to a Notification, including those that are within a batch request.
    70  			if request.ID == nil {
    71  				logger.Debug(
    72  					"HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)",
    73  					"req", request,
    74  				)
    75  				continue
    76  			}
    77  			if len(r.URL.Path) > 1 {
    78  				responses = append(
    79  					responses,
    80  					types.RPCInvalidRequestError(request.ID, fmt.Errorf("path %s is invalid", r.URL.Path)),
    81  				)
    82  				continue
    83  			}
    84  			rpcFunc, ok := funcMap[request.Method]
    85  			if !ok || rpcFunc.ws {
    86  				responses = append(responses, types.RPCMethodNotFoundError(request.ID))
    87  				continue
    88  			}
    89  			ctx := &types.Context{JSONReq: &request, HTTPReq: r}
    90  			args := []reflect.Value{reflect.ValueOf(ctx)}
    91  			if len(request.Params) > 0 {
    92  				fnArgs, err := jsonParamsToArgs(rpcFunc, request.Params)
    93  				if err != nil {
    94  					responses = append(
    95  						responses,
    96  						types.RPCInvalidParamsError(request.ID, fmt.Errorf("error converting json params to arguments: %w", err)),
    97  					)
    98  					continue
    99  				}
   100  				args = append(args, fnArgs...)
   101  			}
   102  			returns := rpcFunc.f.Call(args)
   103  			logger.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns)
   104  			result, err := unreflectResult(returns)
   105  			if err != nil {
   106  				responses = append(responses, types.RPCInternalError(request.ID, err))
   107  				continue
   108  			}
   109  			responses = append(responses, types.NewRPCSuccessResponse(request.ID, result))
   110  		}
   111  		if len(responses) > 0 {
   112  			WriteRPCResponseHTTP(w, responses...)
   113  		}
   114  	}
   115  }
   116  
   117  func handleInvalidJSONRPCPaths(next http.HandlerFunc) http.HandlerFunc {
   118  	return func(w http.ResponseWriter, r *http.Request) {
   119  		// Since the pattern "/" matches all paths not matched by other registered patterns,
   120  		//  we check whether the path is indeed "/", otherwise return a 404 error
   121  		if r.URL.Path != "/" {
   122  			http.NotFound(w, r)
   123  			return
   124  		}
   125  
   126  		next(w, r)
   127  	}
   128  }
   129  
   130  func mapParamsToArgs(
   131  	rpcFunc *RPCFunc,
   132  	params map[string]json.RawMessage,
   133  	argsOffset int,
   134  ) ([]reflect.Value, error) {
   135  
   136  	values := make([]reflect.Value, len(rpcFunc.argNames))
   137  	for i, argName := range rpcFunc.argNames {
   138  		argType := rpcFunc.args[i+argsOffset]
   139  
   140  		if p, ok := params[argName]; ok && p != nil && len(p) > 0 {
   141  			val := reflect.New(argType)
   142  			err := tmjson.Unmarshal(p, val.Interface())
   143  			if err != nil {
   144  				return nil, err
   145  			}
   146  			values[i] = val.Elem()
   147  		} else { // use default for that type
   148  			values[i] = reflect.Zero(argType)
   149  		}
   150  	}
   151  
   152  	return values, nil
   153  }
   154  
   155  func arrayParamsToArgs(
   156  	rpcFunc *RPCFunc,
   157  	params []json.RawMessage,
   158  	argsOffset int,
   159  ) ([]reflect.Value, error) {
   160  
   161  	if len(rpcFunc.argNames) != len(params) {
   162  		return nil, fmt.Errorf("expected %v parameters (%v), got %v (%v)",
   163  			len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)
   164  	}
   165  
   166  	values := make([]reflect.Value, len(params))
   167  	for i, p := range params {
   168  		argType := rpcFunc.args[i+argsOffset]
   169  		val := reflect.New(argType)
   170  		err := tmjson.Unmarshal(p, val.Interface())
   171  		if err != nil {
   172  			return nil, err
   173  		}
   174  		values[i] = val.Elem()
   175  	}
   176  	return values, nil
   177  }
   178  
   179  // raw is unparsed json (from json.RawMessage) encoding either a map or an
   180  // array.
   181  //
   182  // Example:
   183  //   rpcFunc.args = [rpctypes.Context string]
   184  //   rpcFunc.argNames = ["arg"]
   185  func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte) ([]reflect.Value, error) {
   186  	const argsOffset = 1
   187  
   188  	// TODO: Make more efficient, perhaps by checking the first character for '{' or '['?
   189  	// First, try to get the map.
   190  	var m map[string]json.RawMessage
   191  	err := json.Unmarshal(raw, &m)
   192  	if err == nil {
   193  		return mapParamsToArgs(rpcFunc, m, argsOffset)
   194  	}
   195  
   196  	// Otherwise, try an array.
   197  	var a []json.RawMessage
   198  	err = json.Unmarshal(raw, &a)
   199  	if err == nil {
   200  		return arrayParamsToArgs(rpcFunc, a, argsOffset)
   201  	}
   202  
   203  	// Otherwise, bad format, we cannot parse
   204  	return nil, fmt.Errorf("unknown type for JSON params: %v. Expected map or array", err)
   205  }
   206  
   207  // writes a list of available rpc endpoints as an html page
   208  func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) {
   209  	noArgNames := []string{}
   210  	argNames := []string{}
   211  	for name, funcData := range funcMap {
   212  		if len(funcData.args) == 0 {
   213  			noArgNames = append(noArgNames, name)
   214  		} else {
   215  			argNames = append(argNames, name)
   216  		}
   217  	}
   218  	sort.Strings(noArgNames)
   219  	sort.Strings(argNames)
   220  	buf := new(bytes.Buffer)
   221  	buf.WriteString("<html><body>")
   222  	buf.WriteString("<br>Available endpoints:<br>")
   223  
   224  	for _, name := range noArgNames {
   225  		link := fmt.Sprintf("//%s/%s", r.Host, name)
   226  		buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
   227  	}
   228  
   229  	buf.WriteString("<br>Endpoints that require arguments:<br>")
   230  	for _, name := range argNames {
   231  		link := fmt.Sprintf("//%s/%s?", r.Host, name)
   232  		funcData := funcMap[name]
   233  		for i, argName := range funcData.argNames {
   234  			link += argName + "=_"
   235  			if i < len(funcData.argNames)-1 {
   236  				link += "&"
   237  			}
   238  		}
   239  		buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link))
   240  	}
   241  	buf.WriteString("</body></html>")
   242  	w.Header().Set("Content-Type", "text/html")
   243  	w.WriteHeader(200)
   244  	w.Write(buf.Bytes()) // nolint: errcheck
   245  }