]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/client_test.go
net/http: speed up tests, use t.Parallel when it's safe
[gostls13.git] / src / net / http / client_test.go
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 // Tests for client.go
6
7 package http_test
8
9 import (
10         "bytes"
11         "context"
12         "crypto/tls"
13         "crypto/x509"
14         "encoding/base64"
15         "errors"
16         "fmt"
17         "io"
18         "io/ioutil"
19         "log"
20         "net"
21         . "net/http"
22         "net/http/cookiejar"
23         "net/http/httptest"
24         "net/url"
25         "reflect"
26         "strconv"
27         "strings"
28         "sync"
29         "testing"
30         "time"
31 )
32
33 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
34         w.Header().Set("Last-Modified", "sometime")
35         fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
36 })
37
38 // pedanticReadAll works like ioutil.ReadAll but additionally
39 // verifies that r obeys the documented io.Reader contract.
40 func pedanticReadAll(r io.Reader) (b []byte, err error) {
41         var bufa [64]byte
42         buf := bufa[:]
43         for {
44                 n, err := r.Read(buf)
45                 if n == 0 && err == nil {
46                         return nil, fmt.Errorf("Read: n=0 with err=nil")
47                 }
48                 b = append(b, buf[:n]...)
49                 if err == io.EOF {
50                         n, err := r.Read(buf)
51                         if n != 0 || err != io.EOF {
52                                 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
53                         }
54                         return b, nil
55                 }
56                 if err != nil {
57                         return b, err
58                 }
59         }
60 }
61
62 type chanWriter chan string
63
64 func (w chanWriter) Write(p []byte) (n int, err error) {
65         w <- string(p)
66         return len(p), nil
67 }
68
69 func TestClient(t *testing.T) {
70         defer afterTest(t)
71         ts := httptest.NewServer(robotsTxtHandler)
72         defer ts.Close()
73
74         r, err := Get(ts.URL)
75         var b []byte
76         if err == nil {
77                 b, err = pedanticReadAll(r.Body)
78                 r.Body.Close()
79         }
80         if err != nil {
81                 t.Error(err)
82         } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
83                 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
84         }
85 }
86
87 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
88 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
89
90 func testClientHead(t *testing.T, h2 bool) {
91         defer afterTest(t)
92         cst := newClientServerTest(t, h2, robotsTxtHandler)
93         defer cst.close()
94
95         r, err := cst.c.Head(cst.ts.URL)
96         if err != nil {
97                 t.Fatal(err)
98         }
99         if _, ok := r.Header["Last-Modified"]; !ok {
100                 t.Error("Last-Modified header not found.")
101         }
102 }
103
104 type recordingTransport struct {
105         req *Request
106 }
107
108 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
109         t.req = req
110         return nil, errors.New("dummy impl")
111 }
112
113 func TestGetRequestFormat(t *testing.T) {
114         defer afterTest(t)
115         tr := &recordingTransport{}
116         client := &Client{Transport: tr}
117         url := "http://dummy.faketld/"
118         client.Get(url) // Note: doesn't hit network
119         if tr.req.Method != "GET" {
120                 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
121         }
122         if tr.req.URL.String() != url {
123                 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
124         }
125         if tr.req.Header == nil {
126                 t.Errorf("expected non-nil request Header")
127         }
128 }
129
130 func TestPostRequestFormat(t *testing.T) {
131         defer afterTest(t)
132         tr := &recordingTransport{}
133         client := &Client{Transport: tr}
134
135         url := "http://dummy.faketld/"
136         json := `{"key":"value"}`
137         b := strings.NewReader(json)
138         client.Post(url, "application/json", b) // Note: doesn't hit network
139
140         if tr.req.Method != "POST" {
141                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
142         }
143         if tr.req.URL.String() != url {
144                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
145         }
146         if tr.req.Header == nil {
147                 t.Fatalf("expected non-nil request Header")
148         }
149         if tr.req.Close {
150                 t.Error("got Close true, want false")
151         }
152         if g, e := tr.req.ContentLength, int64(len(json)); g != e {
153                 t.Errorf("got ContentLength %d, want %d", g, e)
154         }
155 }
156
157 func TestPostFormRequestFormat(t *testing.T) {
158         defer afterTest(t)
159         tr := &recordingTransport{}
160         client := &Client{Transport: tr}
161
162         urlStr := "http://dummy.faketld/"
163         form := make(url.Values)
164         form.Set("foo", "bar")
165         form.Add("foo", "bar2")
166         form.Set("bar", "baz")
167         client.PostForm(urlStr, form) // Note: doesn't hit network
168
169         if tr.req.Method != "POST" {
170                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
171         }
172         if tr.req.URL.String() != urlStr {
173                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
174         }
175         if tr.req.Header == nil {
176                 t.Fatalf("expected non-nil request Header")
177         }
178         if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
179                 t.Errorf("got Content-Type %q, want %q", g, e)
180         }
181         if tr.req.Close {
182                 t.Error("got Close true, want false")
183         }
184         // Depending on map iteration, body can be either of these.
185         expectedBody := "foo=bar&foo=bar2&bar=baz"
186         expectedBody1 := "bar=baz&foo=bar&foo=bar2"
187         if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
188                 t.Errorf("got ContentLength %d, want %d", g, e)
189         }
190         bodyb, err := ioutil.ReadAll(tr.req.Body)
191         if err != nil {
192                 t.Fatalf("ReadAll on req.Body: %v", err)
193         }
194         if g := string(bodyb); g != expectedBody && g != expectedBody1 {
195                 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
196         }
197 }
198
199 func TestClientRedirects(t *testing.T) {
200         setParallel(t)
201         defer afterTest(t)
202         var ts *httptest.Server
203         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
204                 n, _ := strconv.Atoi(r.FormValue("n"))
205                 // Test Referer header. (7 is arbitrary position to test at)
206                 if n == 7 {
207                         if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
208                                 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
209                         }
210                 }
211                 if n < 15 {
212                         Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
213                         return
214                 }
215                 fmt.Fprintf(w, "n=%d", n)
216         }))
217         defer ts.Close()
218
219         c := &Client{}
220         _, err := c.Get(ts.URL)
221         if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
222                 t.Errorf("with default client Get, expected error %q, got %q", e, g)
223         }
224
225         // HEAD request should also have the ability to follow redirects.
226         _, err = c.Head(ts.URL)
227         if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
228                 t.Errorf("with default client Head, expected error %q, got %q", e, g)
229         }
230
231         // Do should also follow redirects.
232         greq, _ := NewRequest("GET", ts.URL, nil)
233         _, err = c.Do(greq)
234         if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
235                 t.Errorf("with default client Do, expected error %q, got %q", e, g)
236         }
237
238         // Requests with an empty Method should also redirect (Issue 12705)
239         greq.Method = ""
240         _, err = c.Do(greq)
241         if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
242                 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
243         }
244
245         var checkErr error
246         var lastVia []*Request
247         var lastReq *Request
248         c = &Client{CheckRedirect: func(req *Request, via []*Request) error {
249                 lastReq = req
250                 lastVia = via
251                 return checkErr
252         }}
253         res, err := c.Get(ts.URL)
254         if err != nil {
255                 t.Fatalf("Get error: %v", err)
256         }
257         res.Body.Close()
258         finalUrl := res.Request.URL.String()
259         if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
260                 t.Errorf("with custom client, expected error %q, got %q", e, g)
261         }
262         if !strings.HasSuffix(finalUrl, "/?n=15") {
263                 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
264         }
265         if e, g := 15, len(lastVia); e != g {
266                 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
267         }
268
269         // Test that Request.Cancel is propagated between requests (Issue 14053)
270         creq, _ := NewRequest("HEAD", ts.URL, nil)
271         cancel := make(chan struct{})
272         creq.Cancel = cancel
273         if _, err := c.Do(creq); err != nil {
274                 t.Fatal(err)
275         }
276         if lastReq == nil {
277                 t.Fatal("didn't see redirect")
278         }
279         if lastReq.Cancel != cancel {
280                 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
281         }
282
283         checkErr = errors.New("no redirects allowed")
284         res, err = c.Get(ts.URL)
285         if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
286                 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
287         }
288         if res == nil {
289                 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
290         }
291         res.Body.Close()
292         if res.Header.Get("Location") == "" {
293                 t.Errorf("no Location header in Response")
294         }
295 }
296
297 func TestClientRedirectContext(t *testing.T) {
298         setParallel(t)
299         defer afterTest(t)
300         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
301                 Redirect(w, r, "/", StatusTemporaryRedirect)
302         }))
303         defer ts.Close()
304
305         ctx, cancel := context.WithCancel(context.Background())
306         c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
307                 cancel()
308                 if len(via) > 2 {
309                         return errors.New("too many redirects")
310                 }
311                 return nil
312         }}
313         req, _ := NewRequest("GET", ts.URL, nil)
314         req = req.WithContext(ctx)
315         _, err := c.Do(req)
316         ue, ok := err.(*url.Error)
317         if !ok {
318                 t.Fatalf("got error %T; want *url.Error", err)
319         }
320         if ue.Err != context.Canceled {
321                 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
322         }
323 }
324
325 type redirectTest struct {
326         suffix       string
327         want         int // response code
328         redirectBody string
329 }
330
331 func TestPostRedirects(t *testing.T) {
332         postRedirectTests := []redirectTest{
333                 {"/", 200, "first"},
334                 {"/?code=301&next=302", 200, "c301"},
335                 {"/?code=302&next=302", 200, "c302"},
336                 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
337                 {"/?code=304", 304, "c304"},
338                 {"/?code=305", 305, "c305"},
339                 {"/?code=307&next=303,308,302", 200, "c307"},
340                 {"/?code=308&next=302,301", 200, "c308"},
341                 {"/?code=404", 404, "c404"},
342         }
343
344         wantSegments := []string{
345                 `POST / "first"`,
346                 `POST /?code=301&next=302 "c301"`,
347                 `GET /?code=302 "c301"`,
348                 `GET / "c301"`,
349                 `POST /?code=302&next=302 "c302"`,
350                 `GET /?code=302 "c302"`,
351                 `GET / "c302"`,
352                 `POST /?code=303&next=301 "c303wc301"`,
353                 `GET /?code=301 "c303wc301"`,
354                 `GET / "c303wc301"`,
355                 `POST /?code=304 "c304"`,
356                 `POST /?code=305 "c305"`,
357                 `POST /?code=307&next=303,308,302 "c307"`,
358                 `POST /?code=303&next=308,302 "c307"`,
359                 `GET /?code=308&next=302 "c307"`,
360                 `GET /?code=302 "c307"`,
361                 `GET / "c307"`,
362                 `POST /?code=308&next=302,301 "c308"`,
363                 `POST /?code=302&next=301 "c308"`,
364                 `GET /?code=301 "c308"`,
365                 `GET / "c308"`,
366                 `POST /?code=404 "c404"`,
367         }
368         want := strings.Join(wantSegments, "\n")
369         testRedirectsByMethod(t, "POST", postRedirectTests, want)
370 }
371
372 func TestDeleteRedirects(t *testing.T) {
373         deleteRedirectTests := []redirectTest{
374                 {"/", 200, "first"},
375                 {"/?code=301&next=302,308", 200, "c301"},
376                 {"/?code=302&next=302", 200, "c302"},
377                 {"/?code=303", 200, "c303"},
378                 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
379                 {"/?code=308&next=307", 200, "c308"},
380                 {"/?code=404", 404, "c404"},
381         }
382
383         wantSegments := []string{
384                 `DELETE / "first"`,
385                 `DELETE /?code=301&next=302,308 "c301"`,
386                 `GET /?code=302&next=308 "c301"`,
387                 `GET /?code=308 "c301"`,
388                 `GET / "c301"`,
389                 `DELETE /?code=302&next=302 "c302"`,
390                 `GET /?code=302 "c302"`,
391                 `GET / "c302"`,
392                 `DELETE /?code=303 "c303"`,
393                 `GET / "c303"`,
394                 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
395                 `DELETE /?code=301&next=308,303,302,304 "c307"`,
396                 `GET /?code=308&next=303,302,304 "c307"`,
397                 `GET /?code=303&next=302,304 "c307"`,
398                 `GET /?code=302&next=304 "c307"`,
399                 `GET /?code=304 "c307"`,
400                 `DELETE /?code=308&next=307 "c308"`,
401                 `DELETE /?code=307 "c308"`,
402                 `DELETE / "c308"`,
403                 `DELETE /?code=404 "c404"`,
404         }
405         want := strings.Join(wantSegments, "\n")
406         testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
407 }
408
409 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
410         defer afterTest(t)
411         var log struct {
412                 sync.Mutex
413                 bytes.Buffer
414         }
415         var ts *httptest.Server
416         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
417                 log.Lock()
418                 slurp, _ := ioutil.ReadAll(r.Body)
419                 fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
420                 log.Unlock()
421                 urlQuery := r.URL.Query()
422                 if v := urlQuery.Get("code"); v != "" {
423                         location := ts.URL
424                         if final := urlQuery.Get("next"); final != "" {
425                                 splits := strings.Split(final, ",")
426                                 first, rest := splits[0], splits[1:]
427                                 location = fmt.Sprintf("%s?code=%s", location, first)
428                                 if len(rest) > 0 {
429                                         location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
430                                 }
431                         }
432                         code, _ := strconv.Atoi(v)
433                         if code/100 == 3 {
434                                 w.Header().Set("Location", location)
435                         }
436                         w.WriteHeader(code)
437                 }
438         }))
439         defer ts.Close()
440
441         for _, tt := range table {
442                 content := tt.redirectBody
443                 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
444                 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
445                 res, err := DefaultClient.Do(req)
446
447                 if err != nil {
448                         t.Fatal(err)
449                 }
450                 if res.StatusCode != tt.want {
451                         t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
452                 }
453         }
454         log.Lock()
455         got := log.String()
456         log.Unlock()
457
458         got = strings.TrimSpace(got)
459         want = strings.TrimSpace(want)
460
461         if got != want {
462                 t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
463         }
464 }
465
466 func TestClientRedirectUseResponse(t *testing.T) {
467         setParallel(t)
468         defer afterTest(t)
469         const body = "Hello, world."
470         var ts *httptest.Server
471         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
472                 if strings.Contains(r.URL.Path, "/other") {
473                         io.WriteString(w, "wrong body")
474                 } else {
475                         w.Header().Set("Location", ts.URL+"/other")
476                         w.WriteHeader(StatusFound)
477                         io.WriteString(w, body)
478                 }
479         }))
480         defer ts.Close()
481
482         c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
483                 if req.Response == nil {
484                         t.Error("expected non-nil Request.Response")
485                 }
486                 return ErrUseLastResponse
487         }}
488         res, err := c.Get(ts.URL)
489         if err != nil {
490                 t.Fatal(err)
491         }
492         if res.StatusCode != StatusFound {
493                 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
494         }
495         defer res.Body.Close()
496         slurp, err := ioutil.ReadAll(res.Body)
497         if err != nil {
498                 t.Fatal(err)
499         }
500         if string(slurp) != body {
501                 t.Errorf("body = %q; want %q", slurp, body)
502         }
503 }
504
505 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
506 // have a Location header.
507 func TestClientRedirect308NoLocation(t *testing.T) {
508         setParallel(t)
509         defer afterTest(t)
510         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
511                 w.Header().Set("Foo", "Bar")
512                 w.WriteHeader(308)
513         }))
514         defer ts.Close()
515         res, err := Get(ts.URL)
516         if err != nil {
517                 t.Fatal(err)
518         }
519         res.Body.Close()
520         if res.StatusCode != 308 {
521                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
522         }
523         if got := res.Header.Get("Foo"); got != "Bar" {
524                 t.Errorf("Foo header = %q; want Bar", got)
525         }
526 }
527
528 // Don't follow a 307/308 if we can't resent the request body.
529 func TestClientRedirect308NoGetBody(t *testing.T) {
530         setParallel(t)
531         defer afterTest(t)
532         const fakeURL = "https://localhost:1234/" // won't be hit
533         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
534                 w.Header().Set("Location", fakeURL)
535                 w.WriteHeader(308)
536         }))
537         defer ts.Close()
538         req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
539         if err != nil {
540                 t.Fatal(err)
541         }
542         req.GetBody = nil // so it can't rewind.
543         res, err := DefaultClient.Do(req)
544         if err != nil {
545                 t.Fatal(err)
546         }
547         res.Body.Close()
548         if res.StatusCode != 308 {
549                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
550         }
551         if got := res.Header.Get("Location"); got != fakeURL {
552                 t.Errorf("Location header = %q; want %q", got, fakeURL)
553         }
554 }
555
556 var expectedCookies = []*Cookie{
557         {Name: "ChocolateChip", Value: "tasty"},
558         {Name: "First", Value: "Hit"},
559         {Name: "Second", Value: "Hit"},
560 }
561
562 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
563         for _, cookie := range r.Cookies() {
564                 SetCookie(w, cookie)
565         }
566         if r.URL.Path == "/" {
567                 SetCookie(w, expectedCookies[1])
568                 Redirect(w, r, "/second", StatusMovedPermanently)
569         } else {
570                 SetCookie(w, expectedCookies[2])
571                 w.Write([]byte("hello"))
572         }
573 })
574
575 func TestClientSendsCookieFromJar(t *testing.T) {
576         defer afterTest(t)
577         tr := &recordingTransport{}
578         client := &Client{Transport: tr}
579         client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
580         us := "http://dummy.faketld/"
581         u, _ := url.Parse(us)
582         client.Jar.SetCookies(u, expectedCookies)
583
584         client.Get(us) // Note: doesn't hit network
585         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
586
587         client.Head(us) // Note: doesn't hit network
588         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
589
590         client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
591         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
592
593         client.PostForm(us, url.Values{}) // Note: doesn't hit network
594         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
595
596         req, _ := NewRequest("GET", us, nil)
597         client.Do(req) // Note: doesn't hit network
598         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
599
600         req, _ = NewRequest("POST", us, nil)
601         client.Do(req) // Note: doesn't hit network
602         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
603 }
604
605 // Just enough correctness for our redirect tests. Uses the URL.Host as the
606 // scope of all cookies.
607 type TestJar struct {
608         m      sync.Mutex
609         perURL map[string][]*Cookie
610 }
611
612 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
613         j.m.Lock()
614         defer j.m.Unlock()
615         if j.perURL == nil {
616                 j.perURL = make(map[string][]*Cookie)
617         }
618         j.perURL[u.Host] = cookies
619 }
620
621 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
622         j.m.Lock()
623         defer j.m.Unlock()
624         return j.perURL[u.Host]
625 }
626
627 func TestRedirectCookiesJar(t *testing.T) {
628         defer afterTest(t)
629         var ts *httptest.Server
630         ts = httptest.NewServer(echoCookiesRedirectHandler)
631         defer ts.Close()
632         c := &Client{
633                 Jar: new(TestJar),
634         }
635         u, _ := url.Parse(ts.URL)
636         c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
637         resp, err := c.Get(ts.URL)
638         if err != nil {
639                 t.Fatalf("Get: %v", err)
640         }
641         resp.Body.Close()
642         matchReturnedCookies(t, expectedCookies, resp.Cookies())
643 }
644
645 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
646         if len(given) != len(expected) {
647                 t.Logf("Received cookies: %v", given)
648                 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
649         }
650         for _, ec := range expected {
651                 foundC := false
652                 for _, c := range given {
653                         if ec.Name == c.Name && ec.Value == c.Value {
654                                 foundC = true
655                                 break
656                         }
657                 }
658                 if !foundC {
659                         t.Errorf("Missing cookie %v", ec)
660                 }
661         }
662 }
663
664 func TestJarCalls(t *testing.T) {
665         defer afterTest(t)
666         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
667                 pathSuffix := r.RequestURI[1:]
668                 if r.RequestURI == "/nosetcookie" {
669                         return // don't set cookies for this path
670                 }
671                 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
672                 if r.RequestURI == "/" {
673                         Redirect(w, r, "http://secondhost.fake/secondpath", 302)
674                 }
675         }))
676         defer ts.Close()
677         jar := new(RecordingJar)
678         c := &Client{
679                 Jar: jar,
680                 Transport: &Transport{
681                         Dial: func(_ string, _ string) (net.Conn, error) {
682                                 return net.Dial("tcp", ts.Listener.Addr().String())
683                         },
684                 },
685         }
686         _, err := c.Get("http://firsthost.fake/")
687         if err != nil {
688                 t.Fatal(err)
689         }
690         _, err = c.Get("http://firsthost.fake/nosetcookie")
691         if err != nil {
692                 t.Fatal(err)
693         }
694         got := jar.log.String()
695         want := `Cookies("http://firsthost.fake/")
696 SetCookie("http://firsthost.fake/", [name=val])
697 Cookies("http://secondhost.fake/secondpath")
698 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
699 Cookies("http://firsthost.fake/nosetcookie")
700 `
701         if got != want {
702                 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
703         }
704 }
705
706 // RecordingJar keeps a log of calls made to it, without
707 // tracking any cookies.
708 type RecordingJar struct {
709         mu  sync.Mutex
710         log bytes.Buffer
711 }
712
713 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
714         j.logf("SetCookie(%q, %v)\n", u, cookies)
715 }
716
717 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
718         j.logf("Cookies(%q)\n", u)
719         return nil
720 }
721
722 func (j *RecordingJar) logf(format string, args ...interface{}) {
723         j.mu.Lock()
724         defer j.mu.Unlock()
725         fmt.Fprintf(&j.log, format, args...)
726 }
727
728 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
729 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
730
731 func testStreamingGet(t *testing.T, h2 bool) {
732         defer afterTest(t)
733         say := make(chan string)
734         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
735                 w.(Flusher).Flush()
736                 for str := range say {
737                         w.Write([]byte(str))
738                         w.(Flusher).Flush()
739                 }
740         }))
741         defer cst.close()
742
743         c := cst.c
744         res, err := c.Get(cst.ts.URL)
745         if err != nil {
746                 t.Fatal(err)
747         }
748         var buf [10]byte
749         for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
750                 say <- str
751                 n, err := io.ReadFull(res.Body, buf[0:len(str)])
752                 if err != nil {
753                         t.Fatalf("ReadFull on %q: %v", str, err)
754                 }
755                 if n != len(str) {
756                         t.Fatalf("Receiving %q, only read %d bytes", str, n)
757                 }
758                 got := string(buf[0:n])
759                 if got != str {
760                         t.Fatalf("Expected %q, got %q", str, got)
761                 }
762         }
763         close(say)
764         _, err = io.ReadFull(res.Body, buf[0:1])
765         if err != io.EOF {
766                 t.Fatalf("at end expected EOF, got %v", err)
767         }
768 }
769
770 type writeCountingConn struct {
771         net.Conn
772         count *int
773 }
774
775 func (c *writeCountingConn) Write(p []byte) (int, error) {
776         *c.count++
777         return c.Conn.Write(p)
778 }
779
780 // TestClientWrites verifies that client requests are buffered and we
781 // don't send a TCP packet per line of the http request + body.
782 func TestClientWrites(t *testing.T) {
783         defer afterTest(t)
784         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
785         }))
786         defer ts.Close()
787
788         writes := 0
789         dialer := func(netz string, addr string) (net.Conn, error) {
790                 c, err := net.Dial(netz, addr)
791                 if err == nil {
792                         c = &writeCountingConn{c, &writes}
793                 }
794                 return c, err
795         }
796         c := &Client{Transport: &Transport{Dial: dialer}}
797
798         _, err := c.Get(ts.URL)
799         if err != nil {
800                 t.Fatal(err)
801         }
802         if writes != 1 {
803                 t.Errorf("Get request did %d Write calls, want 1", writes)
804         }
805
806         writes = 0
807         _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
808         if err != nil {
809                 t.Fatal(err)
810         }
811         if writes != 1 {
812                 t.Errorf("Post request did %d Write calls, want 1", writes)
813         }
814 }
815
816 func TestClientInsecureTransport(t *testing.T) {
817         setParallel(t)
818         defer afterTest(t)
819         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
820                 w.Write([]byte("Hello"))
821         }))
822         errc := make(chanWriter, 10) // but only expecting 1
823         ts.Config.ErrorLog = log.New(errc, "", 0)
824         defer ts.Close()
825
826         // TODO(bradfitz): add tests for skipping hostname checks too?
827         // would require a new cert for testing, and probably
828         // redundant with these tests.
829         for _, insecure := range []bool{true, false} {
830                 tr := &Transport{
831                         TLSClientConfig: &tls.Config{
832                                 InsecureSkipVerify: insecure,
833                         },
834                 }
835                 defer tr.CloseIdleConnections()
836                 c := &Client{Transport: tr}
837                 res, err := c.Get(ts.URL)
838                 if (err == nil) != insecure {
839                         t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
840                 }
841                 if res != nil {
842                         res.Body.Close()
843                 }
844         }
845
846         select {
847         case v := <-errc:
848                 if !strings.Contains(v, "TLS handshake error") {
849                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
850                 }
851         case <-time.After(5 * time.Second):
852                 t.Errorf("timeout waiting for logged error")
853         }
854
855 }
856
857 func TestClientErrorWithRequestURI(t *testing.T) {
858         defer afterTest(t)
859         req, _ := NewRequest("GET", "http://localhost:1234/", nil)
860         req.RequestURI = "/this/field/is/illegal/and/should/error/"
861         _, err := DefaultClient.Do(req)
862         if err == nil {
863                 t.Fatalf("expected an error")
864         }
865         if !strings.Contains(err.Error(), "RequestURI") {
866                 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
867         }
868 }
869
870 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
871         certs := x509.NewCertPool()
872         for _, c := range ts.TLS.Certificates {
873                 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
874                 if err != nil {
875                         t.Fatalf("error parsing server's root cert: %v", err)
876                 }
877                 for _, root := range roots {
878                         certs.AddCert(root)
879                 }
880         }
881         return &Transport{
882                 TLSClientConfig: &tls.Config{RootCAs: certs},
883         }
884 }
885
886 func TestClientWithCorrectTLSServerName(t *testing.T) {
887         defer afterTest(t)
888
889         const serverName = "example.com"
890         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
891                 if r.TLS.ServerName != serverName {
892                         t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
893                 }
894         }))
895         defer ts.Close()
896
897         trans := newTLSTransport(t, ts)
898         trans.TLSClientConfig.ServerName = serverName
899         c := &Client{Transport: trans}
900         if _, err := c.Get(ts.URL); err != nil {
901                 t.Fatalf("expected successful TLS connection, got error: %v", err)
902         }
903 }
904
905 func TestClientWithIncorrectTLSServerName(t *testing.T) {
906         defer afterTest(t)
907         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
908         defer ts.Close()
909         errc := make(chanWriter, 10) // but only expecting 1
910         ts.Config.ErrorLog = log.New(errc, "", 0)
911
912         trans := newTLSTransport(t, ts)
913         trans.TLSClientConfig.ServerName = "badserver"
914         c := &Client{Transport: trans}
915         _, err := c.Get(ts.URL)
916         if err == nil {
917                 t.Fatalf("expected an error")
918         }
919         if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
920                 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
921         }
922         select {
923         case v := <-errc:
924                 if !strings.Contains(v, "TLS handshake error") {
925                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
926                 }
927         case <-time.After(5 * time.Second):
928                 t.Errorf("timeout waiting for logged error")
929         }
930 }
931
932 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
933 // when not empty.
934 //
935 // tls.Config.ServerName (non-empty, set to "example.com") takes
936 // precedence over "some-other-host.tld" which previously incorrectly
937 // took precedence. We don't actually connect to (or even resolve)
938 // "some-other-host.tld", though, because of the Transport.Dial hook.
939 //
940 // The httptest.Server has a cert with "example.com" as its name.
941 func TestTransportUsesTLSConfigServerName(t *testing.T) {
942         defer afterTest(t)
943         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
944                 w.Write([]byte("Hello"))
945         }))
946         defer ts.Close()
947
948         tr := newTLSTransport(t, ts)
949         tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
950         tr.Dial = func(netw, addr string) (net.Conn, error) {
951                 return net.Dial(netw, ts.Listener.Addr().String())
952         }
953         defer tr.CloseIdleConnections()
954         c := &Client{Transport: tr}
955         res, err := c.Get("https://some-other-host.tld/")
956         if err != nil {
957                 t.Fatal(err)
958         }
959         res.Body.Close()
960 }
961
962 func TestResponseSetsTLSConnectionState(t *testing.T) {
963         defer afterTest(t)
964         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
965                 w.Write([]byte("Hello"))
966         }))
967         defer ts.Close()
968
969         tr := newTLSTransport(t, ts)
970         tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
971         tr.Dial = func(netw, addr string) (net.Conn, error) {
972                 return net.Dial(netw, ts.Listener.Addr().String())
973         }
974         defer tr.CloseIdleConnections()
975         c := &Client{Transport: tr}
976         res, err := c.Get("https://example.com/")
977         if err != nil {
978                 t.Fatal(err)
979         }
980         defer res.Body.Close()
981         if res.TLS == nil {
982                 t.Fatal("Response didn't set TLS Connection State.")
983         }
984         if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
985                 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
986         }
987 }
988
989 // Check that an HTTPS client can interpret a particular TLS error
990 // to determine that the server is speaking HTTP.
991 // See golang.org/issue/11111.
992 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
993         defer afterTest(t)
994         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
995         defer ts.Close()
996
997         _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
998         if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
999                 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1000         }
1001 }
1002
1003 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1004 func TestClientHeadContentLength_h1(t *testing.T) {
1005         testClientHeadContentLength(t, h1Mode)
1006 }
1007
1008 func TestClientHeadContentLength_h2(t *testing.T) {
1009         testClientHeadContentLength(t, h2Mode)
1010 }
1011
1012 func testClientHeadContentLength(t *testing.T, h2 bool) {
1013         defer afterTest(t)
1014         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1015                 if v := r.FormValue("cl"); v != "" {
1016                         w.Header().Set("Content-Length", v)
1017                 }
1018         }))
1019         defer cst.close()
1020         tests := []struct {
1021                 suffix string
1022                 want   int64
1023         }{
1024                 {"/?cl=1234", 1234},
1025                 {"/?cl=0", 0},
1026                 {"", -1},
1027         }
1028         for _, tt := range tests {
1029                 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1030                 res, err := cst.c.Do(req)
1031                 if err != nil {
1032                         t.Fatal(err)
1033                 }
1034                 if res.ContentLength != tt.want {
1035                         t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1036                 }
1037                 bs, err := ioutil.ReadAll(res.Body)
1038                 if err != nil {
1039                         t.Fatal(err)
1040                 }
1041                 if len(bs) != 0 {
1042                         t.Errorf("Unexpected content: %q", bs)
1043                 }
1044         }
1045 }
1046
1047 func TestEmptyPasswordAuth(t *testing.T) {
1048         defer afterTest(t)
1049         gopher := "gopher"
1050         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1051                 auth := r.Header.Get("Authorization")
1052                 if strings.HasPrefix(auth, "Basic ") {
1053                         encoded := auth[6:]
1054                         decoded, err := base64.StdEncoding.DecodeString(encoded)
1055                         if err != nil {
1056                                 t.Fatal(err)
1057                         }
1058                         expected := gopher + ":"
1059                         s := string(decoded)
1060                         if expected != s {
1061                                 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1062                         }
1063                 } else {
1064                         t.Errorf("Invalid auth %q", auth)
1065                 }
1066         }))
1067         defer ts.Close()
1068         c := &Client{}
1069         req, err := NewRequest("GET", ts.URL, nil)
1070         if err != nil {
1071                 t.Fatal(err)
1072         }
1073         req.URL.User = url.User(gopher)
1074         resp, err := c.Do(req)
1075         if err != nil {
1076                 t.Fatal(err)
1077         }
1078         defer resp.Body.Close()
1079 }
1080
1081 func TestBasicAuth(t *testing.T) {
1082         defer afterTest(t)
1083         tr := &recordingTransport{}
1084         client := &Client{Transport: tr}
1085
1086         url := "http://My%20User:My%20Pass@dummy.faketld/"
1087         expected := "My User:My Pass"
1088         client.Get(url)
1089
1090         if tr.req.Method != "GET" {
1091                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1092         }
1093         if tr.req.URL.String() != url {
1094                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1095         }
1096         if tr.req.Header == nil {
1097                 t.Fatalf("expected non-nil request Header")
1098         }
1099         auth := tr.req.Header.Get("Authorization")
1100         if strings.HasPrefix(auth, "Basic ") {
1101                 encoded := auth[6:]
1102                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1103                 if err != nil {
1104                         t.Fatal(err)
1105                 }
1106                 s := string(decoded)
1107                 if expected != s {
1108                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1109                 }
1110         } else {
1111                 t.Errorf("Invalid auth %q", auth)
1112         }
1113 }
1114
1115 func TestBasicAuthHeadersPreserved(t *testing.T) {
1116         defer afterTest(t)
1117         tr := &recordingTransport{}
1118         client := &Client{Transport: tr}
1119
1120         // If Authorization header is provided, username in URL should not override it
1121         url := "http://My%20User@dummy.faketld/"
1122         req, err := NewRequest("GET", url, nil)
1123         if err != nil {
1124                 t.Fatal(err)
1125         }
1126         req.SetBasicAuth("My User", "My Pass")
1127         expected := "My User:My Pass"
1128         client.Do(req)
1129
1130         if tr.req.Method != "GET" {
1131                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1132         }
1133         if tr.req.URL.String() != url {
1134                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1135         }
1136         if tr.req.Header == nil {
1137                 t.Fatalf("expected non-nil request Header")
1138         }
1139         auth := tr.req.Header.Get("Authorization")
1140         if strings.HasPrefix(auth, "Basic ") {
1141                 encoded := auth[6:]
1142                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1143                 if err != nil {
1144                         t.Fatal(err)
1145                 }
1146                 s := string(decoded)
1147                 if expected != s {
1148                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1149                 }
1150         } else {
1151                 t.Errorf("Invalid auth %q", auth)
1152         }
1153
1154 }
1155
1156 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1157 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1158
1159 func testClientTimeout(t *testing.T, h2 bool) {
1160         if testing.Short() {
1161                 t.Skip("skipping in short mode")
1162         }
1163         defer afterTest(t)
1164         sawRoot := make(chan bool, 1)
1165         sawSlow := make(chan bool, 1)
1166         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1167                 if r.URL.Path == "/" {
1168                         sawRoot <- true
1169                         Redirect(w, r, "/slow", StatusFound)
1170                         return
1171                 }
1172                 if r.URL.Path == "/slow" {
1173                         w.Write([]byte("Hello"))
1174                         w.(Flusher).Flush()
1175                         sawSlow <- true
1176                         time.Sleep(2 * time.Second)
1177                         return
1178                 }
1179         }))
1180         defer cst.close()
1181         const timeout = 500 * time.Millisecond
1182         cst.c.Timeout = timeout
1183
1184         res, err := cst.c.Get(cst.ts.URL)
1185         if err != nil {
1186                 t.Fatal(err)
1187         }
1188
1189         select {
1190         case <-sawRoot:
1191                 // good.
1192         default:
1193                 t.Fatal("handler never got / request")
1194         }
1195
1196         select {
1197         case <-sawSlow:
1198                 // good.
1199         default:
1200                 t.Fatal("handler never got /slow request")
1201         }
1202
1203         errc := make(chan error, 1)
1204         go func() {
1205                 _, err := ioutil.ReadAll(res.Body)
1206                 errc <- err
1207                 res.Body.Close()
1208         }()
1209
1210         const failTime = timeout * 2
1211         select {
1212         case err := <-errc:
1213                 if err == nil {
1214                         t.Fatal("expected error from ReadAll")
1215                 }
1216                 ne, ok := err.(net.Error)
1217                 if !ok {
1218                         t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1219                 } else if !ne.Timeout() {
1220                         t.Errorf("net.Error.Timeout = false; want true")
1221                 }
1222                 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1223                         t.Errorf("error string = %q; missing timeout substring", got)
1224                 }
1225         case <-time.After(failTime):
1226                 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1227         }
1228 }
1229
1230 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1231 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1232
1233 // Client.Timeout firing before getting to the body
1234 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1235         if testing.Short() {
1236                 t.Skip("skipping in short mode")
1237         }
1238         defer afterTest(t)
1239         donec := make(chan bool)
1240         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1241                 <-donec
1242         }))
1243         defer cst.close()
1244         // Note that we use a channel send here and not a close.
1245         // The race detector doesn't know that we're waiting for a timeout
1246         // and thinks that the waitgroup inside httptest.Server is added to concurrently
1247         // with us closing it. If we timed out immediately, we could close the testserver
1248         // before we entered the handler. We're not timing out immediately and there's
1249         // no way we would be done before we entered the handler, but the race detector
1250         // doesn't know this, so synchronize explicitly.
1251         defer func() { donec <- true }()
1252
1253         cst.c.Timeout = 500 * time.Millisecond
1254         _, err := cst.c.Get(cst.ts.URL)
1255         if err == nil {
1256                 t.Fatal("got response from Get; expected error")
1257         }
1258         if _, ok := err.(*url.Error); !ok {
1259                 t.Fatalf("Got error of type %T; want *url.Error", err)
1260         }
1261         ne, ok := err.(net.Error)
1262         if !ok {
1263                 t.Fatalf("Got error of type %T; want some net.Error", err)
1264         }
1265         if !ne.Timeout() {
1266                 t.Error("net.Error.Timeout = false; want true")
1267         }
1268         if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1269                 t.Errorf("error string = %q; missing timeout substring", got)
1270         }
1271 }
1272
1273 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1274 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1275 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1276         setParallel(t)
1277         defer afterTest(t)
1278         saw := make(chan string, 2)
1279         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1280                 saw <- r.RemoteAddr
1281                 if r.URL.Path == "/" {
1282                         Redirect(w, r, "/foo", StatusFound) // which includes a body
1283                 }
1284         }))
1285         defer cst.close()
1286
1287         res, err := cst.c.Get(cst.ts.URL)
1288         if err != nil {
1289                 t.Fatal(err)
1290         }
1291         _, err = ioutil.ReadAll(res.Body)
1292         if err != nil {
1293                 t.Fatal(err)
1294         }
1295         res.Body.Close()
1296
1297         var first string
1298         select {
1299         case first = <-saw:
1300         default:
1301                 t.Fatal("server didn't see a request")
1302         }
1303
1304         var second string
1305         select {
1306         case second = <-saw:
1307         default:
1308                 t.Fatal("server didn't see a second request")
1309         }
1310
1311         if first != second {
1312                 t.Fatal("server saw different client ports before & after the redirect")
1313         }
1314 }
1315
1316 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1317 type eofReaderFunc func()
1318
1319 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1320         f()
1321         return 0, io.EOF
1322 }
1323
1324 func TestReferer(t *testing.T) {
1325         tests := []struct {
1326                 lastReq, newReq string // from -> to URLs
1327                 want            string
1328         }{
1329                 // don't send user:
1330                 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1331                 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1332
1333                 // don't send a user and password:
1334                 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1335                 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1336
1337                 // nothing to do:
1338                 {"http://test.com", "http://link.com", "http://test.com"},
1339                 {"https://test.com", "https://link.com", "https://test.com"},
1340
1341                 // https to http doesn't send a referer:
1342                 {"https://test.com", "http://link.com", ""},
1343                 {"https://gopher:go@test.com", "http://link.com", ""},
1344         }
1345         for _, tt := range tests {
1346                 l, err := url.Parse(tt.lastReq)
1347                 if err != nil {
1348                         t.Fatal(err)
1349                 }
1350                 n, err := url.Parse(tt.newReq)
1351                 if err != nil {
1352                         t.Fatal(err)
1353                 }
1354                 r := ExportRefererForURL(l, n)
1355                 if r != tt.want {
1356                         t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1357                 }
1358         }
1359 }
1360
1361 // issue15577Tripper returns a Response with a redirect response
1362 // header and doesn't populate its Response.Request field.
1363 type issue15577Tripper struct{}
1364
1365 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1366         resp := &Response{
1367                 StatusCode: 303,
1368                 Header:     map[string][]string{"Location": {"http://www.example.com/"}},
1369                 Body:       ioutil.NopCloser(strings.NewReader("")),
1370         }
1371         return resp, nil
1372 }
1373
1374 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1375 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1376         c := &Client{
1377                 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1378                 Transport:     issue15577Tripper{},
1379         }
1380         // Check that this doesn't crash:
1381         c.Get("http://dummy.tld")
1382 }
1383
1384 // Issue 4800: copy (some) headers when Client follows a redirect
1385 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1386         const (
1387                 ua   = "some-agent/1.2"
1388                 xfoo = "foo-val"
1389         )
1390         var ts2URL string
1391         ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1392                 want := Header{
1393                         "User-Agent":      []string{ua},
1394                         "X-Foo":           []string{xfoo},
1395                         "Referer":         []string{ts2URL},
1396                         "Accept-Encoding": []string{"gzip"},
1397                 }
1398                 if !reflect.DeepEqual(r.Header, want) {
1399                         t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1400                 }
1401                 if t.Failed() {
1402                         w.Header().Set("Result", "got errors")
1403                 } else {
1404                         w.Header().Set("Result", "ok")
1405                 }
1406         }))
1407         defer ts1.Close()
1408         ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1409                 Redirect(w, r, ts1.URL, StatusFound)
1410         }))
1411         defer ts2.Close()
1412         ts2URL = ts2.URL
1413
1414         tr := &Transport{}
1415         defer tr.CloseIdleConnections()
1416         c := &Client{
1417                 Transport: tr,
1418                 CheckRedirect: func(r *Request, via []*Request) error {
1419                         want := Header{
1420                                 "User-Agent": []string{ua},
1421                                 "X-Foo":      []string{xfoo},
1422                                 "Referer":    []string{ts2URL},
1423                         }
1424                         if !reflect.DeepEqual(r.Header, want) {
1425                                 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1426                         }
1427                         return nil
1428                 },
1429         }
1430
1431         req, _ := NewRequest("GET", ts2.URL, nil)
1432         req.Header.Add("User-Agent", ua)
1433         req.Header.Add("X-Foo", xfoo)
1434         req.Header.Add("Cookie", "foo=bar")
1435         req.Header.Add("Authorization", "secretpassword")
1436         res, err := c.Do(req)
1437         if err != nil {
1438                 t.Fatal(err)
1439         }
1440         defer res.Body.Close()
1441         if res.StatusCode != 200 {
1442                 t.Fatal(res.Status)
1443         }
1444         if got := res.Header.Get("Result"); got != "ok" {
1445                 t.Errorf("result = %q; want ok", got)
1446         }
1447 }
1448
1449 // Issue 17494: cookies should be altered when Client follows redirects.
1450 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1451         cookieMap := func(cs []*Cookie) map[string][]string {
1452                 m := make(map[string][]string)
1453                 for _, c := range cs {
1454                         m[c.Name] = append(m[c.Name], c.Value)
1455                 }
1456                 return m
1457         }
1458
1459         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1460                 var want map[string][]string
1461                 got := cookieMap(r.Cookies())
1462
1463                 c, _ := r.Cookie("Cycle")
1464                 switch c.Value {
1465                 case "0":
1466                         want = map[string][]string{
1467                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1468                                 "Cookie2": {"OldValue2"},
1469                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1470                                 "Cookie4": {"OldValue4"},
1471                                 "Cycle":   {"0"},
1472                         }
1473                         SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1474                         SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1475                         Redirect(w, r, "/", StatusFound)
1476                 case "1":
1477                         want = map[string][]string{
1478                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1479                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1480                                 "Cookie4": {"OldValue4"},
1481                                 "Cycle":   {"1"},
1482                         }
1483                         SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1484                         SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1485                         SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1486                         Redirect(w, r, "/", StatusFound)
1487                 case "2":
1488                         want = map[string][]string{
1489                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1490                                 "Cookie3": {"NewValue3"},
1491                                 "Cookie4": {"NewValue4"},
1492                                 "Cycle":   {"2"},
1493                         }
1494                         SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1495                         SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1496                         Redirect(w, r, "/", StatusFound)
1497                 case "3":
1498                         want = map[string][]string{
1499                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1500                                 "Cookie3": {"NewValue3"},
1501                                 "Cookie4": {"NewValue4"},
1502                                 "Cookie5": {"NewValue5"},
1503                                 "Cycle":   {"3"},
1504                         }
1505                         // Don't redirect to ensure the loop ends.
1506                 default:
1507                         t.Errorf("unexpected redirect cycle")
1508                         return
1509                 }
1510
1511                 if !reflect.DeepEqual(got, want) {
1512                         t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1513                 }
1514         }))
1515         defer ts.Close()
1516
1517         tr := &Transport{}
1518         defer tr.CloseIdleConnections()
1519         jar, _ := cookiejar.New(nil)
1520         c := &Client{
1521                 Transport: tr,
1522                 Jar:       jar,
1523         }
1524
1525         u, _ := url.Parse(ts.URL)
1526         req, _ := NewRequest("GET", ts.URL, nil)
1527         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1528         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1529         req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1530         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1531         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1532         jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1533         jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1534         res, err := c.Do(req)
1535         if err != nil {
1536                 t.Fatal(err)
1537         }
1538         defer res.Body.Close()
1539         if res.StatusCode != 200 {
1540                 t.Fatal(res.Status)
1541         }
1542 }
1543
1544 // Part of Issue 4800
1545 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1546         tests := []struct {
1547                 header     string
1548                 initialURL string
1549                 destURL    string
1550                 want       bool
1551         }{
1552                 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1553                 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1554
1555                 // Sensitive headers:
1556                 {"cookie", "http://foo.com/", "http://bar.com/", false},
1557                 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1558                 {"authorization", "http://foo.com/", "http://bar.com/", false},
1559                 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1560
1561                 // But subdomains should work:
1562                 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1563                 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1564                 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1565                 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1566                 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1567         }
1568         for i, tt := range tests {
1569                 u0, err := url.Parse(tt.initialURL)
1570                 if err != nil {
1571                         t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1572                         continue
1573                 }
1574                 u1, err := url.Parse(tt.destURL)
1575                 if err != nil {
1576                         t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1577                         continue
1578                 }
1579                 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1580                 if got != tt.want {
1581                         t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1582                                 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1583                 }
1584         }
1585 }
1586
1587 func TestClientRedirectTypes(t *testing.T) {
1588         setParallel(t)
1589         defer afterTest(t)
1590
1591         tests := [...]struct {
1592                 method       string
1593                 serverStatus int
1594                 wantMethod   string // desired subsequent client method
1595         }{
1596                 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1597                 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1598                 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1599                 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1600                 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1601
1602                 5: {method: "HEAD", serverStatus: 301, wantMethod: "GET"},
1603                 6: {method: "HEAD", serverStatus: 302, wantMethod: "GET"},
1604                 7: {method: "HEAD", serverStatus: 303, wantMethod: "GET"},
1605                 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1606                 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1607
1608                 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1609                 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1610                 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1611                 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1612                 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1613
1614                 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1615                 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1616                 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1617                 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1618                 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1619
1620                 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1621                 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1622                 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1623                 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1624                 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1625
1626                 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1627                 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1628                 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1629                 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1630                 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1631         }
1632
1633         handlerc := make(chan HandlerFunc, 1)
1634
1635         ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1636                 h := <-handlerc
1637                 h(rw, req)
1638         }))
1639         defer ts.Close()
1640
1641         for i, tt := range tests {
1642                 handlerc <- func(w ResponseWriter, r *Request) {
1643                         w.Header().Set("Location", ts.URL)
1644                         w.WriteHeader(tt.serverStatus)
1645                 }
1646
1647                 req, err := NewRequest(tt.method, ts.URL, nil)
1648                 if err != nil {
1649                         t.Errorf("#%d: NewRequest: %v", i, err)
1650                         continue
1651                 }
1652
1653                 c := &Client{}
1654                 c.CheckRedirect = func(req *Request, via []*Request) error {
1655                         if got, want := req.Method, tt.wantMethod; got != want {
1656                                 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1657                         }
1658                         handlerc <- func(rw ResponseWriter, req *Request) {
1659                                 // TODO: Check that the body is valid when we do 307 and 308 support
1660                         }
1661                         return nil
1662                 }
1663
1664                 res, err := c.Do(req)
1665                 if err != nil {
1666                         t.Errorf("#%d: Response: %v", i, err)
1667                         continue
1668                 }
1669
1670                 res.Body.Close()
1671         }
1672 }