github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/net/http/internal/chunked.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // The wire protocol for HTTP's "chunked" Transfer-Encoding. 6 7 // Package internal contains HTTP internals shared by net/http and 8 // net/http/httputil. 9 package internal 10 11 import ( 12 "bufio" 13 "bytes" 14 "errors" 15 "fmt" 16 "io" 17 ) 18 19 const maxLineLength = 4096 // assumed <= bufio.defaultBufSize 20 21 var ErrLineTooLong = errors.New("header line too long") 22 23 // NewChunkedReader returns a new chunkedReader that translates the data read from r 24 // out of HTTP "chunked" format before returning it. 25 // The chunkedReader returns io.EOF when the final 0-length chunk is read. 26 // 27 // NewChunkedReader is not needed by normal applications. The http package 28 // automatically decodes chunking when reading response bodies. 29 func NewChunkedReader(r io.Reader) io.Reader { 30 br, ok := r.(*bufio.Reader) 31 if !ok { 32 br = bufio.NewReader(r) 33 } 34 return &chunkedReader{r: br} 35 } 36 37 type chunkedReader struct { 38 r *bufio.Reader 39 n uint64 // unread bytes in chunk 40 err error 41 buf [2]byte 42 } 43 44 func (cr *chunkedReader) beginChunk() { 45 // chunk-size CRLF 46 var line []byte 47 line, cr.err = readChunkLine(cr.r) 48 if cr.err != nil { 49 return 50 } 51 cr.n, cr.err = parseHexUint(line) 52 if cr.err != nil { 53 return 54 } 55 if cr.n == 0 { 56 cr.err = io.EOF 57 } 58 } 59 60 func (cr *chunkedReader) chunkHeaderAvailable() bool { 61 n := cr.r.Buffered() 62 if n > 0 { 63 peek, _ := cr.r.Peek(n) 64 return bytes.IndexByte(peek, '\n') >= 0 65 } 66 return false 67 } 68 69 func (cr *chunkedReader) Read(b []uint8) (n int, err error) { 70 for cr.err == nil { 71 if cr.n == 0 { 72 if n > 0 && !cr.chunkHeaderAvailable() { 73 // We've read enough. Don't potentially block 74 // reading a new chunk header. 75 break 76 } 77 cr.beginChunk() 78 continue 79 } 80 if len(b) == 0 { 81 break 82 } 83 rbuf := b 84 if uint64(len(rbuf)) > cr.n { 85 rbuf = rbuf[:cr.n] 86 } 87 var n0 int 88 n0, cr.err = cr.r.Read(rbuf) 89 n += n0 90 b = b[n0:] 91 cr.n -= uint64(n0) 92 // If we're at the end of a chunk, read the next two 93 // bytes to verify they are "\r\n". 94 if cr.n == 0 && cr.err == nil { 95 if _, cr.err = io.ReadFull(cr.r, cr.buf[:2]); cr.err == nil { 96 if cr.buf[0] != '\r' || cr.buf[1] != '\n' { 97 cr.err = errors.New("malformed chunked encoding") 98 } 99 } 100 } 101 } 102 return n, cr.err 103 } 104 105 // Read a line of bytes (up to \n) from b. 106 // Give up if the line exceeds maxLineLength. 107 // The returned bytes are owned by the bufio.Reader 108 // so they are only valid until the next bufio read. 109 func readChunkLine(b *bufio.Reader) ([]byte, error) { 110 p, err := b.ReadSlice('\n') 111 if err != nil { 112 // We always know when EOF is coming. 113 // If the caller asked for a line, there should be a line. 114 if err == io.EOF { 115 err = io.ErrUnexpectedEOF 116 } else if err == bufio.ErrBufferFull { 117 err = ErrLineTooLong 118 } 119 return nil, err 120 } 121 if len(p) >= maxLineLength { 122 return nil, ErrLineTooLong 123 } 124 p = trimTrailingWhitespace(p) 125 p, err = removeChunkExtension(p) 126 if err != nil { 127 return nil, err 128 } 129 return p, nil 130 } 131 132 func trimTrailingWhitespace(b []byte) []byte { 133 for len(b) > 0 && isASCIISpace(b[len(b)-1]) { 134 b = b[:len(b)-1] 135 } 136 return b 137 } 138 139 func isASCIISpace(b byte) bool { 140 return b == ' ' || b == '\t' || b == '\n' || b == '\r' 141 } 142 143 // removeChunkExtension removes any chunk-extension from p. 144 // For example, 145 // "0" => "0" 146 // "0;token" => "0" 147 // "0;token=val" => "0" 148 // `0;token="quoted string"` => "0" 149 func removeChunkExtension(p []byte) ([]byte, error) { 150 semi := bytes.IndexByte(p, ';') 151 if semi == -1 { 152 return p, nil 153 } 154 // TODO: care about exact syntax of chunk extensions? We're 155 // ignoring and stripping them anyway. For now just never 156 // return an error. 157 return p[:semi], nil 158 } 159 160 // NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP 161 // "chunked" format before writing them to w. Closing the returned chunkedWriter 162 // sends the final 0-length chunk that marks the end of the stream. 163 // 164 // NewChunkedWriter is not needed by normal applications. The http 165 // package adds chunking automatically if handlers don't set a 166 // Content-Length header. Using newChunkedWriter inside a handler 167 // would result in double chunking or chunking with a Content-Length 168 // length, both of which are wrong. 169 func NewChunkedWriter(w io.Writer) io.WriteCloser { 170 return &chunkedWriter{w} 171 } 172 173 // Writing to chunkedWriter translates to writing in HTTP chunked Transfer 174 // Encoding wire format to the underlying Wire chunkedWriter. 175 type chunkedWriter struct { 176 Wire io.Writer 177 } 178 179 // Write the contents of data as one chunk to Wire. 180 // NOTE: Note that the corresponding chunk-writing procedure in Conn.Write has 181 // a bug since it does not check for success of io.WriteString 182 func (cw *chunkedWriter) Write(data []byte) (n int, err error) { 183 184 // Don't send 0-length data. It looks like EOF for chunked encoding. 185 if len(data) == 0 { 186 return 0, nil 187 } 188 189 if _, err = fmt.Fprintf(cw.Wire, "%x\r\n", len(data)); err != nil { 190 return 0, err 191 } 192 if n, err = cw.Wire.Write(data); err != nil { 193 return 194 } 195 if n != len(data) { 196 err = io.ErrShortWrite 197 return 198 } 199 if _, err = io.WriteString(cw.Wire, "\r\n"); err != nil { 200 return 201 } 202 if bw, ok := cw.Wire.(*FlushAfterChunkWriter); ok { 203 err = bw.Flush() 204 } 205 return 206 } 207 208 func (cw *chunkedWriter) Close() error { 209 _, err := io.WriteString(cw.Wire, "0\r\n") 210 return err 211 } 212 213 // FlushAfterChunkWriter signals from the caller of NewChunkedWriter 214 // that each chunk should be followed by a flush. It is used by the 215 // http.Transport code to keep the buffering behavior for headers and 216 // trailers, but flush out chunks aggressively in the middle for 217 // request bodies which may be generated slowly. See Issue 6574. 218 type FlushAfterChunkWriter struct { 219 *bufio.Writer 220 } 221 222 func parseHexUint(v []byte) (n uint64, err error) { 223 for _, b := range v { 224 n <<= 4 225 switch { 226 case '0' <= b && b <= '9': 227 b = b - '0' 228 case 'a' <= b && b <= 'f': 229 b = b - 'a' + 10 230 case 'A' <= b && b <= 'F': 231 b = b - 'A' + 10 232 default: 233 return 0, errors.New("invalid byte in chunk length") 234 } 235 n |= uint64(b) 236 } 237 return 238 }