| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package requestbody |
| 16 | |
| 17 | import ( |
| 18 | "errors" |
| 19 | "io" |
| 20 | "net/http" |
| 21 | "strings" |
| 22 | "time" |
| 23 | |
| 24 | "go.uber.org/zap" |
| 25 | "go.uber.org/zap/zapcore" |
| 26 | |
| 27 | "github.com/caddyserver/caddy/v2" |
| 28 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 29 | ) |
| 30 | |
| 31 | func init() { |
| 32 | caddy.RegisterModule(RequestBody{}) |
| 33 | } |
| 34 | |
| 35 | // RequestBody is a middleware for manipulating the request body. |
| 36 | type RequestBody struct { |
| 37 | // The maximum number of bytes to allow reading from the body by a later handler. |
| 38 | // If more bytes are read, an error with HTTP status 413 is returned. |
| 39 | MaxSize int64 `json:"max_size,omitempty"` |
| 40 | |
| 41 | // EXPERIMENTAL. Subject to change/removal. |
| 42 | ReadTimeout time.Duration `json:"read_timeout,omitempty"` |
| 43 | |
| 44 | // EXPERIMENTAL. Subject to change/removal. |
| 45 | WriteTimeout time.Duration `json:"write_timeout,omitempty"` |
| 46 | |
| 47 | // This field permit to replace body on the fly |
| 48 | // EXPERIMENTAL. Subject to change/removal. |
| 49 | Set string `json:"set,omitempty"` |
| 50 | |
| 51 | logger *zap.Logger |
| 52 | } |
| 53 | |
| 54 | // CaddyModule returns the Caddy module information. |
| 55 | func (RequestBody) CaddyModule() caddy.ModuleInfo { |
| 56 | return caddy.ModuleInfo{ |
| 57 | ID: "http.handlers.request_body", |
| 58 | New: func() caddy.Module { return new(RequestBody) }, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func (rb *RequestBody) Provision(ctx caddy.Context) error { |
| 63 | rb.logger = ctx.Logger() |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { |
| 68 | if rb.Set != "" { |
| 69 | if r.Body != nil { |
| 70 | err := r.Body.Close() |
| 71 | if err != nil { |
| 72 | return err |
| 73 | } |
| 74 | } |
| 75 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 76 | replacedBody := repl.ReplaceAll(rb.Set, "") |
| 77 | r.Body = io.NopCloser(strings.NewReader(replacedBody)) |
| 78 | r.ContentLength = int64(len(replacedBody)) |
| 79 | } |
| 80 | if r.Body == nil { |
| 81 | return next.ServeHTTP(w, r) |
| 82 | } |
| 83 | if rb.MaxSize > 0 { |
| 84 | r.Body = errorWrapper{http.MaxBytesReader(w, r.Body, rb.MaxSize)} |
| 85 | } |
| 86 | if rb.ReadTimeout > 0 || rb.WriteTimeout > 0 { |
| 87 | //nolint:bodyclose |
| 88 | rc := http.NewResponseController(w) |
| 89 | if rb.ReadTimeout > 0 { |
| 90 | if err := rc.SetReadDeadline(time.Now().Add(rb.ReadTimeout)); err != nil { |
| 91 | if c := rb.logger.Check(zapcore.ErrorLevel, "could not set read deadline"); c != nil { |
| 92 | c.Write(zap.Error(err)) |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | if rb.WriteTimeout > 0 { |
| 97 | if err := rc.SetWriteDeadline(time.Now().Add(rb.WriteTimeout)); err != nil { |
| 98 | if c := rb.logger.Check(zapcore.ErrorLevel, "could not set write deadline"); c != nil { |
| 99 | c.Write(zap.Error(err)) |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | return next.ServeHTTP(w, r) |
| 105 | } |
| 106 | |
| 107 | // errorWrapper wraps errors that are returned from Read() |
| 108 | // so that they can be associated with a proper status code. |
| 109 | type errorWrapper struct { |
| 110 | io.ReadCloser |
| 111 | } |
| 112 | |
| 113 | func (ew errorWrapper) Read(p []byte) (n int, err error) { |
| 114 | n, err = ew.ReadCloser.Read(p) |
| 115 | var mbe *http.MaxBytesError |
| 116 | if errors.As(err, &mbe) { |
| 117 | err = caddyhttp.Error(http.StatusRequestEntityTooLarge, err) |
| 118 | } |
| 119 | return n, err |
| 120 | } |
| 121 | |
| 122 | // Interface guard |
| 123 | var _ caddyhttp.MiddlewareHandler = (*RequestBody)(nil) |