libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / net / http / transfer.go
blob4a2bda19facf83d23bf79e51560c100ffc674327
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.
5 package http
7 import (
8 "bufio"
9 "bytes"
10 "errors"
11 "fmt"
12 "io"
13 "io/ioutil"
14 "net/textproto"
15 "strconv"
16 "strings"
17 "sync"
20 // transferWriter inspects the fields of a user-supplied Request or Response,
21 // sanitizes them without changing the user object and provides methods for
22 // writing the respective header, body and trailer in wire format.
23 type transferWriter struct {
24 Method string
25 Body io.Reader
26 BodyCloser io.Closer
27 ResponseToHEAD bool
28 ContentLength int64 // -1 means unknown, 0 means exactly none
29 Close bool
30 TransferEncoding []string
31 Trailer Header
34 func newTransferWriter(r interface{}) (t *transferWriter, err error) {
35 t = &transferWriter{}
37 // Extract relevant fields
38 atLeastHTTP11 := false
39 switch rr := r.(type) {
40 case *Request:
41 if rr.ContentLength != 0 && rr.Body == nil {
42 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
44 t.Method = rr.Method
45 t.Body = rr.Body
46 t.BodyCloser = rr.Body
47 t.ContentLength = rr.ContentLength
48 t.Close = rr.Close
49 t.TransferEncoding = rr.TransferEncoding
50 t.Trailer = rr.Trailer
51 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
52 if t.Body != nil && len(t.TransferEncoding) == 0 && atLeastHTTP11 {
53 if t.ContentLength == 0 {
54 // Test to see if it's actually zero or just unset.
55 var buf [1]byte
56 n, _ := io.ReadFull(t.Body, buf[:])
57 if n == 1 {
58 // Oh, guess there is data in this Body Reader after all.
59 // The ContentLength field just wasn't set.
60 // Stich the Body back together again, re-attaching our
61 // consumed byte.
62 t.ContentLength = -1
63 t.Body = io.MultiReader(bytes.NewBuffer(buf[:]), t.Body)
64 } else {
65 // Body is actually empty.
66 t.Body = nil
67 t.BodyCloser = nil
70 if t.ContentLength < 0 {
71 t.TransferEncoding = []string{"chunked"}
74 case *Response:
75 if rr.Request != nil {
76 t.Method = rr.Request.Method
78 t.Body = rr.Body
79 t.BodyCloser = rr.Body
80 t.ContentLength = rr.ContentLength
81 t.Close = rr.Close
82 t.TransferEncoding = rr.TransferEncoding
83 t.Trailer = rr.Trailer
84 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
85 t.ResponseToHEAD = noBodyExpected(t.Method)
88 // Sanitize Body,ContentLength,TransferEncoding
89 if t.ResponseToHEAD {
90 t.Body = nil
91 if chunked(t.TransferEncoding) {
92 t.ContentLength = -1
94 } else {
95 if !atLeastHTTP11 || t.Body == nil {
96 t.TransferEncoding = nil
98 if chunked(t.TransferEncoding) {
99 t.ContentLength = -1
100 } else if t.Body == nil { // no chunking, no body
101 t.ContentLength = 0
105 // Sanitize Trailer
106 if !chunked(t.TransferEncoding) {
107 t.Trailer = nil
110 return t, nil
113 func noBodyExpected(requestMethod string) bool {
114 return requestMethod == "HEAD"
117 func (t *transferWriter) shouldSendContentLength() bool {
118 if chunked(t.TransferEncoding) {
119 return false
121 if t.ContentLength > 0 {
122 return true
124 // Many servers expect a Content-Length for these methods
125 if t.Method == "POST" || t.Method == "PUT" {
126 return true
128 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
129 return true
132 return false
135 func (t *transferWriter) WriteHeader(w io.Writer) (err error) {
136 if t.Close {
137 _, err = io.WriteString(w, "Connection: close\r\n")
138 if err != nil {
139 return
143 // Write Content-Length and/or Transfer-Encoding whose values are a
144 // function of the sanitized field triple (Body, ContentLength,
145 // TransferEncoding)
146 if t.shouldSendContentLength() {
147 io.WriteString(w, "Content-Length: ")
148 _, err = io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n")
149 if err != nil {
150 return
152 } else if chunked(t.TransferEncoding) {
153 _, err = io.WriteString(w, "Transfer-Encoding: chunked\r\n")
154 if err != nil {
155 return
159 // Write Trailer header
160 if t.Trailer != nil {
161 // TODO: At some point, there should be a generic mechanism for
162 // writing long headers, using HTTP line splitting
163 io.WriteString(w, "Trailer: ")
164 needComma := false
165 for k := range t.Trailer {
166 k = CanonicalHeaderKey(k)
167 switch k {
168 case "Transfer-Encoding", "Trailer", "Content-Length":
169 return &badStringError{"invalid Trailer key", k}
171 if needComma {
172 io.WriteString(w, ",")
174 io.WriteString(w, k)
175 needComma = true
177 _, err = io.WriteString(w, "\r\n")
180 return
183 func (t *transferWriter) WriteBody(w io.Writer) (err error) {
184 var ncopy int64
186 // Write body
187 if t.Body != nil {
188 if chunked(t.TransferEncoding) {
189 cw := newChunkedWriter(w)
190 _, err = io.Copy(cw, t.Body)
191 if err == nil {
192 err = cw.Close()
194 } else if t.ContentLength == -1 {
195 ncopy, err = io.Copy(w, t.Body)
196 } else {
197 ncopy, err = io.Copy(w, io.LimitReader(t.Body, t.ContentLength))
198 if err != nil {
199 return err
201 var nextra int64
202 nextra, err = io.Copy(ioutil.Discard, t.Body)
203 ncopy += nextra
205 if err != nil {
206 return err
208 if err = t.BodyCloser.Close(); err != nil {
209 return err
213 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
214 return fmt.Errorf("http: Request.ContentLength=%d with Body length %d",
215 t.ContentLength, ncopy)
218 // TODO(petar): Place trailer writer code here.
219 if chunked(t.TransferEncoding) {
220 // Last chunk, empty trailer
221 _, err = io.WriteString(w, "\r\n")
224 return
227 type transferReader struct {
228 // Input
229 Header Header
230 StatusCode int
231 RequestMethod string
232 ProtoMajor int
233 ProtoMinor int
234 // Output
235 Body io.ReadCloser
236 ContentLength int64
237 TransferEncoding []string
238 Close bool
239 Trailer Header
242 // bodyAllowedForStatus reports whether a given response status code
243 // permits a body. See RFC2616, section 4.4.
244 func bodyAllowedForStatus(status int) bool {
245 switch {
246 case status >= 100 && status <= 199:
247 return false
248 case status == 204:
249 return false
250 case status == 304:
251 return false
253 return true
256 // msg is *Request or *Response.
257 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
258 t := &transferReader{RequestMethod: "GET"}
260 // Unify input
261 isResponse := false
262 switch rr := msg.(type) {
263 case *Response:
264 t.Header = rr.Header
265 t.StatusCode = rr.StatusCode
266 t.ProtoMajor = rr.ProtoMajor
267 t.ProtoMinor = rr.ProtoMinor
268 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header)
269 isResponse = true
270 if rr.Request != nil {
271 t.RequestMethod = rr.Request.Method
273 case *Request:
274 t.Header = rr.Header
275 t.ProtoMajor = rr.ProtoMajor
276 t.ProtoMinor = rr.ProtoMinor
277 // Transfer semantics for Requests are exactly like those for
278 // Responses with status code 200, responding to a GET method
279 t.StatusCode = 200
280 default:
281 panic("unexpected type")
284 // Default to HTTP/1.1
285 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
286 t.ProtoMajor, t.ProtoMinor = 1, 1
289 // Transfer encoding, content length
290 t.TransferEncoding, err = fixTransferEncoding(t.RequestMethod, t.Header)
291 if err != nil {
292 return err
295 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
296 if err != nil {
297 return err
299 if isResponse && t.RequestMethod == "HEAD" {
300 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
301 return err
302 } else {
303 t.ContentLength = n
305 } else {
306 t.ContentLength = realLength
309 // Trailer
310 t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
311 if err != nil {
312 return err
315 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
316 // and the status is not 1xx, 204 or 304, then the body is unbounded.
317 // See RFC2616, section 4.4.
318 switch msg.(type) {
319 case *Response:
320 if realLength == -1 &&
321 !chunked(t.TransferEncoding) &&
322 bodyAllowedForStatus(t.StatusCode) {
323 // Unbounded body.
324 t.Close = true
328 // Prepare body reader. ContentLength < 0 means chunked encoding
329 // or close connection when finished, since multipart is not supported yet
330 switch {
331 case chunked(t.TransferEncoding):
332 if noBodyExpected(t.RequestMethod) {
333 t.Body = eofReader
334 } else {
335 t.Body = &body{src: newChunkedReader(r), hdr: msg, r: r, closing: t.Close}
337 case realLength == 0:
338 t.Body = eofReader
339 case realLength > 0:
340 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
341 default:
342 // realLength < 0, i.e. "Content-Length" not mentioned in header
343 if t.Close {
344 // Close semantics (i.e. HTTP/1.0)
345 t.Body = &body{src: r, closing: t.Close}
346 } else {
347 // Persistent connection (i.e. HTTP/1.1)
348 t.Body = eofReader
352 // Unify output
353 switch rr := msg.(type) {
354 case *Request:
355 rr.Body = t.Body
356 rr.ContentLength = t.ContentLength
357 rr.TransferEncoding = t.TransferEncoding
358 rr.Close = t.Close
359 rr.Trailer = t.Trailer
360 case *Response:
361 rr.Body = t.Body
362 rr.ContentLength = t.ContentLength
363 rr.TransferEncoding = t.TransferEncoding
364 rr.Close = t.Close
365 rr.Trailer = t.Trailer
368 return nil
371 // Checks whether chunked is part of the encodings stack
372 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
374 // Checks whether the encoding is explicitly "identity".
375 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
377 // Sanitize transfer encoding
378 func fixTransferEncoding(requestMethod string, header Header) ([]string, error) {
379 raw, present := header["Transfer-Encoding"]
380 if !present {
381 return nil, nil
384 delete(header, "Transfer-Encoding")
386 encodings := strings.Split(raw[0], ",")
387 te := make([]string, 0, len(encodings))
388 // TODO: Even though we only support "identity" and "chunked"
389 // encodings, the loop below is designed with foresight. One
390 // invariant that must be maintained is that, if present,
391 // chunked encoding must always come first.
392 for _, encoding := range encodings {
393 encoding = strings.ToLower(strings.TrimSpace(encoding))
394 // "identity" encoding is not recorded
395 if encoding == "identity" {
396 break
398 if encoding != "chunked" {
399 return nil, &badStringError{"unsupported transfer encoding", encoding}
401 te = te[0 : len(te)+1]
402 te[len(te)-1] = encoding
404 if len(te) > 1 {
405 return nil, &badStringError{"too many transfer encodings", strings.Join(te, ",")}
407 if len(te) > 0 {
408 // Chunked encoding trumps Content-Length. See RFC 2616
409 // Section 4.4. Currently len(te) > 0 implies chunked
410 // encoding.
411 delete(header, "Content-Length")
412 return te, nil
415 return nil, nil
418 // Determine the expected body length, using RFC 2616 Section 4.4. This
419 // function is not a method, because ultimately it should be shared by
420 // ReadResponse and ReadRequest.
421 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
423 // Logic based on response type or status
424 if noBodyExpected(requestMethod) {
425 return 0, nil
427 if status/100 == 1 {
428 return 0, nil
430 switch status {
431 case 204, 304:
432 return 0, nil
435 // Logic based on Transfer-Encoding
436 if chunked(te) {
437 return -1, nil
440 // Logic based on Content-Length
441 cl := strings.TrimSpace(header.get("Content-Length"))
442 if cl != "" {
443 n, err := parseContentLength(cl)
444 if err != nil {
445 return -1, err
447 return n, nil
448 } else {
449 header.Del("Content-Length")
452 if !isResponse && requestMethod == "GET" {
453 // RFC 2616 doesn't explicitly permit nor forbid an
454 // entity-body on a GET request so we permit one if
455 // declared, but we default to 0 here (not -1 below)
456 // if there's no mention of a body.
457 return 0, nil
460 // Body-EOF logic based on other methods (like closing, or chunked coding)
461 return -1, nil
464 // Determine whether to hang up after sending a request and body, or
465 // receiving a response and body
466 // 'header' is the request headers
467 func shouldClose(major, minor int, header Header) bool {
468 if major < 1 {
469 return true
470 } else if major == 1 && minor == 0 {
471 if !strings.Contains(strings.ToLower(header.get("Connection")), "keep-alive") {
472 return true
474 return false
475 } else {
476 // TODO: Should split on commas, toss surrounding white space,
477 // and check each field.
478 if strings.ToLower(header.get("Connection")) == "close" {
479 header.Del("Connection")
480 return true
483 return false
486 // Parse the trailer header
487 func fixTrailer(header Header, te []string) (Header, error) {
488 raw := header.get("Trailer")
489 if raw == "" {
490 return nil, nil
493 header.Del("Trailer")
494 trailer := make(Header)
495 keys := strings.Split(raw, ",")
496 for _, key := range keys {
497 key = CanonicalHeaderKey(strings.TrimSpace(key))
498 switch key {
499 case "Transfer-Encoding", "Trailer", "Content-Length":
500 return nil, &badStringError{"bad trailer key", key}
502 trailer.Del(key)
504 if len(trailer) == 0 {
505 return nil, nil
507 if !chunked(te) {
508 // Trailer and no chunking
509 return nil, ErrUnexpectedTrailer
511 return trailer, nil
514 // body turns a Reader into a ReadCloser.
515 // Close ensures that the body has been fully read
516 // and then reads the trailer if necessary.
517 type body struct {
518 src io.Reader
519 hdr interface{} // non-nil (Response or Request) value means read trailer
520 r *bufio.Reader // underlying wire-format reader for the trailer
521 closing bool // is the connection to be closed after reading body?
523 mu sync.Mutex // guards closed, and calls to Read and Close
524 closed bool
527 // ErrBodyReadAfterClose is returned when reading a Request or Response
528 // Body after the body has been closed. This typically happens when the body is
529 // read after an HTTP Handler calls WriteHeader or Write on its
530 // ResponseWriter.
531 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
533 func (b *body) Read(p []byte) (n int, err error) {
534 b.mu.Lock()
535 defer b.mu.Unlock()
536 if b.closed {
537 return 0, ErrBodyReadAfterClose
539 return b.readLocked(p)
542 // Must hold b.mu.
543 func (b *body) readLocked(p []byte) (n int, err error) {
544 n, err = b.src.Read(p)
546 if err == io.EOF {
547 // Chunked case. Read the trailer.
548 if b.hdr != nil {
549 if e := b.readTrailer(); e != nil {
550 err = e
552 b.hdr = nil
553 } else {
554 // If the server declared the Content-Length, our body is a LimitedReader
555 // and we need to check whether this EOF arrived early.
556 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
557 err = io.ErrUnexpectedEOF
562 return n, err
565 var (
566 singleCRLF = []byte("\r\n")
567 doubleCRLF = []byte("\r\n\r\n")
570 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
571 for peekSize := 4; ; peekSize++ {
572 // This loop stops when Peek returns an error,
573 // which it does when r's buffer has been filled.
574 buf, err := r.Peek(peekSize)
575 if bytes.HasSuffix(buf, doubleCRLF) {
576 return true
578 if err != nil {
579 break
582 return false
585 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
587 func (b *body) readTrailer() error {
588 // The common case, since nobody uses trailers.
589 buf, err := b.r.Peek(2)
590 if bytes.Equal(buf, singleCRLF) {
591 b.r.ReadByte()
592 b.r.ReadByte()
593 return nil
595 if len(buf) < 2 {
596 return errTrailerEOF
598 if err != nil {
599 return err
602 // Make sure there's a header terminator coming up, to prevent
603 // a DoS with an unbounded size Trailer. It's not easy to
604 // slip in a LimitReader here, as textproto.NewReader requires
605 // a concrete *bufio.Reader. Also, we can't get all the way
606 // back up to our conn's LimitedReader that *might* be backing
607 // this bufio.Reader. Instead, a hack: we iteratively Peek up
608 // to the bufio.Reader's max size, looking for a double CRLF.
609 // This limits the trailer to the underlying buffer size, typically 4kB.
610 if !seeUpcomingDoubleCRLF(b.r) {
611 return errors.New("http: suspiciously long trailer after chunked body")
614 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
615 if err != nil {
616 if err == io.EOF {
617 return errTrailerEOF
619 return err
621 switch rr := b.hdr.(type) {
622 case *Request:
623 rr.Trailer = Header(hdr)
624 case *Response:
625 rr.Trailer = Header(hdr)
627 return nil
630 func (b *body) Close() error {
631 b.mu.Lock()
632 defer b.mu.Unlock()
633 if b.closed {
634 return nil
636 var err error
637 switch {
638 case b.hdr == nil && b.closing:
639 // no trailer and closing the connection next.
640 // no point in reading to EOF.
641 default:
642 // Fully consume the body, which will also lead to us reading
643 // the trailer headers after the body, if present.
644 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
646 b.closed = true
647 return err
650 // bodyLocked is a io.Reader reading from a *body when its mutex is
651 // already held.
652 type bodyLocked struct {
653 b *body
656 func (bl bodyLocked) Read(p []byte) (n int, err error) {
657 if bl.b.closed {
658 return 0, ErrBodyReadAfterClose
660 return bl.b.readLocked(p)
663 // parseContentLength trims whitespace from s and returns -1 if no value
664 // is set, or the value if it's >= 0.
665 func parseContentLength(cl string) (int64, error) {
666 cl = strings.TrimSpace(cl)
667 if cl == "" {
668 return -1, nil
670 n, err := strconv.ParseInt(cl, 10, 64)
671 if err != nil || n < 0 {
672 return 0, &badStringError{"bad Content-Length", cl}
674 return n, nil