From 931c98f7add66b01b56f9c85ba4e329ab73d67c0 Mon Sep 17 00:00:00 2001 From: Sam Kleinman Date: Tue, 7 Jun 2022 12:40:22 -0400 Subject: [PATCH] rpc: always close http bodies (#8712) Closes #8686 --- rpc/jsonrpc/server/http_json_handler.go | 8 +++++++- rpc/jsonrpc/server/http_json_handler_test.go | 2 +- rpc/jsonrpc/server/rpc_func.go | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/rpc/jsonrpc/server/http_json_handler.go b/rpc/jsonrpc/server/http_json_handler.go index 2eeded2d7..4f9e28faa 100644 --- a/rpc/jsonrpc/server/http_json_handler.go +++ b/rpc/jsonrpc/server/http_json_handler.go @@ -81,9 +81,15 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.Han } } +func ensureBodyClose(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + next(w, r) + } +} + func handleInvalidJSONRPCPaths(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - // Since the pattern "/" matches all paths not matched by other registered patterns, // we check whether the path is indeed "/", otherwise return a 404 error if r.URL.Path != "/" { http.NotFound(w, r) diff --git a/rpc/jsonrpc/server/http_json_handler_test.go b/rpc/jsonrpc/server/http_json_handler_test.go index 77c74ffbc..dd4a9d8e2 100644 --- a/rpc/jsonrpc/server/http_json_handler_test.go +++ b/rpc/jsonrpc/server/http_json_handler_test.go @@ -223,7 +223,7 @@ func TestRPCNotificationInBatch(t *testing.T) { func TestUnknownRPCPath(t *testing.T) { mux := testMux() - req, _ := http.NewRequest("GET", "http://localhost/unknownrpcpath", nil) + req, _ := http.NewRequest("GET", "http://localhost/unknownrpcpath", strings.NewReader("")) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) res := rec.Result() diff --git a/rpc/jsonrpc/server/rpc_func.go b/rpc/jsonrpc/server/rpc_func.go index 1fff323d7..947f8be5b 100644 --- a/rpc/jsonrpc/server/rpc_func.go +++ b/rpc/jsonrpc/server/rpc_func.go @@ -26,11 +26,11 @@ func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger lo if fn.ws { continue // skip websocket endpoints, not usable via GET calls } - mux.HandleFunc("/"+name, makeHTTPHandler(fn, logger)) + mux.HandleFunc("/"+name, ensureBodyClose(makeHTTPHandler(fn, logger))) } // Endpoints for POST. - mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, logger))) + mux.HandleFunc("/", ensureBodyClose(handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, logger)))) } // Function introspection