From 1f3b349ea2df4cd4540ed78d46c9527d454a351e Mon Sep 17 00:00:00 2001 From: Juliusz Chroboczek Date: Sat, 9 Dec 2023 15:51:35 +0100 Subject: [PATCH] Use MaxBytesReader in whip. --- webserver/webserver.go | 10 ++++++++-- webserver/whip.go | 17 ++++------------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/webserver/webserver.go b/webserver/webserver.go index ec9518b..4d869c7 100644 --- a/webserver/webserver.go +++ b/webserver/webserver.go @@ -133,11 +133,17 @@ func httpError(w http.ResponseWriter, err error) { return } if os.IsPermission(err) { - http.Error(w, "403 forbidden", http.StatusForbidden) + http.Error(w, "Forbidden", http.StatusForbidden) + return + } + var mberr *http.MaxBytesError + if errors.As(err, &mberr) { + http.Error(w, "Request body too large", + http.StatusRequestEntityTooLarge) return } log.Printf("HTTP server error: %v", err) - http.Error(w, "500 Internal Server Error", + http.Error(w, "Internal server error", http.StatusInternalServerError) } diff --git a/webserver/whip.go b/webserver/whip.go index aaac79d..7f833f1 100644 --- a/webserver/whip.go +++ b/webserver/whip.go @@ -4,7 +4,6 @@ import ( "bytes" crand "crypto/rand" "encoding/base64" - "errors" "fmt" "io" "log" @@ -44,16 +43,6 @@ func newId() string { return base64.RawURLEncoding.EncodeToString(b) } -const sdpLimit = 1024 * 1024 - -func readLimited(r io.Reader) ([]byte, error) { - v, err := io.ReadAll(io.LimitReader(r, sdpLimit)) - if len(v) == sdpLimit { - err = errors.New("SDP too large") - } - return v, err -} - func canPresent(perms []string) bool { for _, p := range perms { if p == "present" { @@ -119,6 +108,8 @@ func whipICEServers(w http.ResponseWriter) { } } +const sdpLimit = 1024 * 1024 + func whipEndpointHandler(w http.ResponseWriter, r *http.Request) { if redirect(w, r) { return @@ -181,7 +172,7 @@ func whipEndpointHandler(w http.ResponseWriter, r *http.Request) { return } - body, err := readLimited(r.Body) + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, sdpLimit)) if err != nil { httpError(w, err) return @@ -311,7 +302,7 @@ func whipResourceHandler(w http.ResponseWriter, r *http.Request) { return } - body, err := readLimited(r.Body) + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, sdpLimit)) if err != nil { httpError(w, err) return