| 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 caddyhttp |
| 16 | |
| 17 | import ( |
| 18 | "bufio" |
| 19 | "bytes" |
| 20 | "fmt" |
| 21 | "io" |
| 22 | "net" |
| 23 | "net/http" |
| 24 | ) |
| 25 | |
| 26 | // ResponseWriterWrapper wraps an underlying ResponseWriter and |
| 27 | // promotes its Pusher method as well. To use this type, embed |
| 28 | // a pointer to it within your own struct type that implements |
| 29 | // the http.ResponseWriter interface, then call methods on the |
| 30 | // embedded value. |
| 31 | type ResponseWriterWrapper struct { |
| 32 | http.ResponseWriter |
| 33 | } |
| 34 | |
| 35 | // Push implements http.Pusher. It simply calls the underlying |
| 36 | // ResponseWriter's Push method if there is one, or returns |
| 37 | // ErrNotImplemented otherwise. |
| 38 | func (rww *ResponseWriterWrapper) Push(target string, opts *http.PushOptions) error { |
| 39 | if pusher, ok := rww.ResponseWriter.(http.Pusher); ok { |
| 40 | return pusher.Push(target, opts) |
| 41 | } |
| 42 | return ErrNotImplemented |
| 43 | } |
| 44 | |
| 45 | // ReadFrom implements io.ReaderFrom. It retries to use io.ReaderFrom if available, |
| 46 | // then fallback to io.Copy. |
| 47 | // see: https://github.com/caddyserver/caddy/issues/6546 |
| 48 | func (rww *ResponseWriterWrapper) ReadFrom(r io.Reader) (n int64, err error) { |
| 49 | if rf, ok := rww.ResponseWriter.(io.ReaderFrom); ok { |
| 50 | return rf.ReadFrom(r) |
| 51 | } |
| 52 | return io.Copy(rww.ResponseWriter, r) |
| 53 | } |
| 54 | |
| 55 | // Unwrap returns the underlying ResponseWriter, necessary for |
| 56 | // http.ResponseController to work correctly. |
| 57 | func (rww *ResponseWriterWrapper) Unwrap() http.ResponseWriter { |
| 58 | return rww.ResponseWriter |
| 59 | } |
| 60 | |
| 61 | // ErrNotImplemented is returned when an underlying |
| 62 | // ResponseWriter does not implement the required method. |
| 63 | var ErrNotImplemented = fmt.Errorf("method not implemented") |
| 64 | |
| 65 | type responseRecorder struct { |
| 66 | *ResponseWriterWrapper |
| 67 | statusCode int |
| 68 | buf *bytes.Buffer |
| 69 | shouldBuffer ShouldBufferFunc |
| 70 | size int |
| 71 | wroteHeader bool |
| 72 | stream bool |
| 73 | |
| 74 | readSize *int |
| 75 | } |
| 76 | |
| 77 | // NewResponseRecorder returns a new ResponseRecorder that can be |
| 78 | // used instead of a standard http.ResponseWriter. The recorder is |
| 79 | // useful for middlewares which need to buffer a response and |
| 80 | // potentially process its entire body before actually writing the |
| 81 | // response to the underlying writer. Of course, buffering the entire |
| 82 | // body has a memory overhead, but sometimes there is no way to avoid |
| 83 | // buffering the whole response, hence the existence of this type. |
| 84 | // Still, if at all practical, handlers should strive to stream |
| 85 | // responses by wrapping Write and WriteHeader methods instead of |
| 86 | // buffering whole response bodies. |
| 87 | // |
| 88 | // Buffering is actually optional. The shouldBuffer function will |
| 89 | // be called just before the headers are written. If it returns |
| 90 | // true, the headers and body will be buffered by this recorder |
| 91 | // and not written to the underlying writer; if false, the headers |
| 92 | // will be written immediately and the body will be streamed out |
| 93 | // directly to the underlying writer. If shouldBuffer is nil, |
| 94 | // the response will never be buffered and will always be streamed |
| 95 | // directly to the writer. |
| 96 | // |
| 97 | // You can know if shouldBuffer returned true by calling Buffered(). |
| 98 | // |
| 99 | // The provided buffer buf should be obtained from a pool for best |
| 100 | // performance (see the sync.Pool type). |
| 101 | // |
| 102 | // Proper usage of a recorder looks like this: |
| 103 | // |
| 104 | // rec := caddyhttp.NewResponseRecorder(w, buf, shouldBuffer) |
| 105 | // err := next.ServeHTTP(rec, req) |
| 106 | // if err != nil { |
| 107 | // return err |
| 108 | // } |
| 109 | // if !rec.Buffered() { |
| 110 | // return nil |
| 111 | // } |
| 112 | // // process the buffered response here |
| 113 | // |
| 114 | // The header map is not buffered; i.e. the ResponseRecorder's Header() |
| 115 | // method returns the same header map of the underlying ResponseWriter. |
| 116 | // This is a crucial design decision to allow HTTP trailers to be |
| 117 | // flushed properly (https://github.com/caddyserver/caddy/issues/3236). |
| 118 | // |
| 119 | // Once you are ready to write the response, there are two ways you can |
| 120 | // do it. The easier way is to have the recorder do it: |
| 121 | // |
| 122 | // rec.WriteResponse() |
| 123 | // |
| 124 | // This writes the recorded response headers as well as the buffered body. |
| 125 | // Or, you may wish to do it yourself, especially if you manipulated the |
| 126 | // buffered body. First you will need to write the headers with the |
| 127 | // recorded status code, then write the body (this example writes the |
| 128 | // recorder's body buffer, but you might have your own body to write |
| 129 | // instead): |
| 130 | // |
| 131 | // w.WriteHeader(rec.Status()) |
| 132 | // io.Copy(w, rec.Buffer()) |
| 133 | // |
| 134 | // As a special case, 1xx responses are not buffered nor recorded |
| 135 | // because they are not the final response; they are passed through |
| 136 | // directly to the underlying ResponseWriter. |
| 137 | func NewResponseRecorder(w http.ResponseWriter, buf *bytes.Buffer, shouldBuffer ShouldBufferFunc) ResponseRecorder { |
| 138 | return &responseRecorder{ |
| 139 | ResponseWriterWrapper: &ResponseWriterWrapper{ResponseWriter: w}, |
| 140 | buf: buf, |
| 141 | shouldBuffer: shouldBuffer, |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // WriteHeader writes the headers with statusCode to the wrapped |
| 146 | // ResponseWriter unless the response is to be buffered instead. |
| 147 | // 1xx responses are never buffered. |
| 148 | func (rr *responseRecorder) WriteHeader(statusCode int) { |
| 149 | if rr.wroteHeader { |
| 150 | return |
| 151 | } |
| 152 | |
| 153 | // save statusCode always, in case HTTP middleware upgrades websocket |
| 154 | // connections by manually setting headers and writing status 101 |
| 155 | rr.statusCode = statusCode |
| 156 | |
| 157 | // decide whether we should buffer the response |
| 158 | if rr.shouldBuffer == nil { |
| 159 | rr.stream = true |
| 160 | } else { |
| 161 | rr.stream = !rr.shouldBuffer(rr.statusCode, rr.ResponseWriterWrapper.Header()) |
| 162 | } |
| 163 | |
| 164 | // 1xx responses aren't final; just informational |
| 165 | if statusCode < 100 || statusCode > 199 { |
| 166 | rr.wroteHeader = true |
| 167 | } |
| 168 | |
| 169 | // if informational or not buffered, immediately write header |
| 170 | if rr.stream || (100 <= statusCode && statusCode <= 199) { |
| 171 | rr.ResponseWriterWrapper.WriteHeader(statusCode) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | func (rr *responseRecorder) Write(data []byte) (int, error) { |
| 176 | rr.WriteHeader(http.StatusOK) |
| 177 | var n int |
| 178 | var err error |
| 179 | if rr.stream { |
| 180 | n, err = rr.ResponseWriterWrapper.Write(data) |
| 181 | } else { |
| 182 | n, err = rr.buf.Write(data) |
| 183 | } |
| 184 | |
| 185 | rr.size += n |
| 186 | return n, err |
| 187 | } |
| 188 | |
| 189 | func (rr *responseRecorder) ReadFrom(r io.Reader) (int64, error) { |
| 190 | rr.WriteHeader(http.StatusOK) |
| 191 | var n int64 |
| 192 | var err error |
| 193 | if rr.stream { |
| 194 | n, err = rr.ResponseWriterWrapper.ReadFrom(r) |
| 195 | } else { |
| 196 | n, err = rr.buf.ReadFrom(r) |
| 197 | } |
| 198 | |
| 199 | rr.size += int(n) |
| 200 | return n, err |
| 201 | } |
| 202 | |
| 203 | // Status returns the status code that was written, if any. |
| 204 | func (rr *responseRecorder) Status() int { |
| 205 | return rr.statusCode |
| 206 | } |
| 207 | |
| 208 | // Size returns the number of bytes written, |
| 209 | // not including the response headers. |
| 210 | func (rr *responseRecorder) Size() int { |
| 211 | return rr.size |
| 212 | } |
| 213 | |
| 214 | // Buffer returns the body buffer that rr was created with. |
| 215 | // You should still have your original pointer, though. |
| 216 | func (rr *responseRecorder) Buffer() *bytes.Buffer { |
| 217 | return rr.buf |
| 218 | } |
| 219 | |
| 220 | // Buffered returns whether rr has decided to buffer the response. |
| 221 | func (rr *responseRecorder) Buffered() bool { |
| 222 | return !rr.stream |
| 223 | } |
| 224 | |
| 225 | func (rr *responseRecorder) WriteResponse() error { |
| 226 | if rr.statusCode == 0 { |
| 227 | // could happen if no handlers actually wrote anything, |
| 228 | // and this prevents a panic; status must be > 0 |
| 229 | rr.WriteHeader(http.StatusOK) |
| 230 | } |
| 231 | if rr.stream { |
| 232 | return nil |
| 233 | } |
| 234 | rr.ResponseWriterWrapper.WriteHeader(rr.statusCode) |
| 235 | _, err := io.Copy(rr.ResponseWriterWrapper, rr.buf) |
| 236 | return err |
| 237 | } |
| 238 | |
| 239 | // FlushError will suppress actual flushing if the response is buffered. See: |
| 240 | // https://github.com/caddyserver/caddy/issues/6144 |
| 241 | func (rr *responseRecorder) FlushError() error { |
| 242 | if rr.stream { |
| 243 | //nolint:bodyclose |
| 244 | return http.NewResponseController(rr.ResponseWriterWrapper).Flush() |
| 245 | } |
| 246 | return nil |
| 247 | } |
| 248 | |
| 249 | // Private interface so it can only be used in this package |
| 250 | // #TODO: maybe export it later |
| 251 | func (rr *responseRecorder) setReadSize(size *int) { |
| 252 | rr.readSize = size |
| 253 | } |
| 254 | |
| 255 | func (rr *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| 256 | //nolint:bodyclose |
| 257 | conn, brw, err := http.NewResponseController(rr.ResponseWriterWrapper).Hijack() |
| 258 | if err != nil { |
| 259 | return nil, nil, err |
| 260 | } |
| 261 | // Per http documentation, returned bufio.Writer is empty, but bufio.Read maybe not |
| 262 | conn = &hijackedConn{conn, rr} |
| 263 | brw.Writer.Reset(conn) |
| 264 | |
| 265 | buffered := brw.Reader.Buffered() |
| 266 | if buffered != 0 { |
| 267 | conn.(*hijackedConn).updateReadSize(buffered) |
| 268 | data, _ := brw.Peek(buffered) |
| 269 | brw.Reader.Reset(io.MultiReader(bytes.NewReader(data), conn)) |
| 270 | // peek to make buffered data appear, as Reset will make it 0 |
| 271 | _, _ = brw.Peek(buffered) |
| 272 | } else { |
| 273 | brw.Reader.Reset(conn) |
| 274 | } |
| 275 | return conn, brw, nil |
| 276 | } |
| 277 | |
| 278 | // used to track the size of hijacked response writers |
| 279 | type hijackedConn struct { |
| 280 | net.Conn |
| 281 | rr *responseRecorder |
| 282 | } |
| 283 | |
| 284 | func (hc *hijackedConn) updateReadSize(n int) { |
| 285 | if hc.rr.readSize != nil { |
| 286 | *hc.rr.readSize += n |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | func (hc *hijackedConn) Read(p []byte) (int, error) { |
| 291 | n, err := hc.Conn.Read(p) |
| 292 | hc.updateReadSize(n) |
| 293 | return n, err |
| 294 | } |
| 295 | |
| 296 | func (hc *hijackedConn) WriteTo(w io.Writer) (int64, error) { |
| 297 | n, err := io.Copy(w, hc.Conn) |
| 298 | hc.updateReadSize(int(n)) |
| 299 | return n, err |
| 300 | } |
| 301 | |
| 302 | func (hc *hijackedConn) Write(p []byte) (int, error) { |
| 303 | n, err := hc.Conn.Write(p) |
| 304 | hc.rr.size += n |
| 305 | return n, err |
| 306 | } |
| 307 | |
| 308 | func (hc *hijackedConn) ReadFrom(r io.Reader) (int64, error) { |
| 309 | n, err := io.Copy(hc.Conn, r) |
| 310 | hc.rr.size += int(n) |
| 311 | return n, err |
| 312 | } |
| 313 | |
| 314 | // ResponseRecorder is a http.ResponseWriter that records |
| 315 | // responses instead of writing them to the client. See |
| 316 | // docs for NewResponseRecorder for proper usage. |
| 317 | type ResponseRecorder interface { |
| 318 | http.ResponseWriter |
| 319 | Status() int |
| 320 | Buffer() *bytes.Buffer |
| 321 | Buffered() bool |
| 322 | Size() int |
| 323 | WriteResponse() error |
| 324 | } |
| 325 | |
| 326 | // ShouldBufferFunc is a function that returns true if the |
| 327 | // response should be buffered, given the pending HTTP status |
| 328 | // code and response headers. |
| 329 | type ShouldBufferFunc func(status int, header http.Header) bool |
| 330 | |
| 331 | // Interface guards |
| 332 | var ( |
| 333 | _ http.ResponseWriter = (*ResponseWriterWrapper)(nil) |
| 334 | _ ResponseRecorder = (*responseRecorder)(nil) |
| 335 | |
| 336 | // Implementing ReaderFrom can be such a significant |
| 337 | // optimization that it should probably be required! |
| 338 | // see PR #5022 (25%-50% speedup) |
| 339 | _ io.ReaderFrom = (*ResponseWriterWrapper)(nil) |
| 340 | _ io.ReaderFrom = (*responseRecorder)(nil) |
| 341 | _ io.ReaderFrom = (*hijackedConn)(nil) |
| 342 | |
| 343 | _ io.WriterTo = (*hijackedConn)(nil) |
| 344 | ) |