diff --git a/defs/bytes_counter.go b/defs/bytes_counter.go index 4d17de1..8b6625b 100644 --- a/defs/bytes_counter.go +++ b/defs/bytes_counter.go @@ -29,6 +29,11 @@ func (c *BytesCounter) Write(p []byte) (int, error) { return n, nil } +// Discount takes back n bytes that were counted for a request that failed. +func (c *BytesCounter) Discount(n uint64) { + c.total.Add(^(n - 1)) +} + // SetBase sets the base for dividing bytes into megabyte or mebibyte func (c *BytesCounter) SetMebi(mebi bool) { c.mebi = mebi diff --git a/defs/server.go b/defs/server.go index 40dc958..81f97ce 100644 --- a/defs/server.go +++ b/defs/server.go @@ -418,10 +418,11 @@ func (s *Server) Download(silent bool, useBytes, useMebi bool, requests int, chu downloadDone := make(chan int, requests) var wg sync.WaitGroup - // the last error of a failed request, returned when no request got an - // answer, so a broken path is not reported as a 0 Mbps result - var lastErr atomic.Pointer[error] + // whether any request was answered with data, and why the last one that + // was not failed var succeeded atomic.Bool + var lastErr atomic.Pointer[error] + var failed bool // one read buffer per worker, reused by its replacement requests: only // one request per worker runs at a time @@ -430,30 +431,55 @@ func (s *Server) Download(silent bool, useBytes, useMebi bool, requests int, chu bufs[i] = make([]byte, downloadReadSize) } - doDownload := func(worker int) { - defer wg.Done() - - reqClone := req.Clone(WithWorker(ctx, worker)) - resp, err := http.DefaultClient.Do(reqClone) + // fetch makes one download request for a worker. An error means it + // brought no test data: the request failed, or the answer was not a + // success. + fetch := func(worker int) error { + resp, err := http.DefaultClient.Do(req.Clone(WithWorker(ctx, worker))) if err != nil { - if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - output.WriteDebug("Failed when making HTTP request: %s\n", err) - } - if ctx.Err() == nil { - lastErr.Store(&err) - } - return + return err } defer resp.Body.Close() - succeeded.Store(true) + + if err := refusal("download", resp); err != nil { + // an error page is not test data, so it is not counted + return err + } // io.Copy into io.Discard would read in 8 KiB chunks (its ReadFrom), // and Go's HTTP/2 client sends a WINDOW_UPDATE frame, in its own // write, after every read that frees 4 KiB. Hiding ReadFrom makes // CopyBuffer read into the larger buffer instead. - if _, err = io.CopyBuffer(struct{ io.Writer }{io.Discard}, io.TeeReader(resp.Body, counter), bufs[worker]); err != nil { - if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - output.WriteDebug("Failed when reading HTTP response: %s\n", err) + n, err := io.CopyBuffer(struct{ io.Writer }{io.Discard}, io.TeeReader(resp.Body, counter), bufs[worker]) + if n == 0 { + // success without a single byte is not test data either + if err == nil { + err = errors.New("the download request returned no data") + } + return err + } + // A body that was cut short counts all the same, whoever cut it: + // the end of the test, --timeout or the server. What arrived did + // cross the link, and on a slow link no request gets its whole body. + succeeded.Store(true) + if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { + output.WriteDebug("Failed when reading HTTP response: %s\n", err) + } + return nil + } + + doDownload := func(worker int) { + defer wg.Done() + + if err := fetch(worker); err != nil { + // cancellation is how the test ends, so it is not a failure + if ctx.Err() != nil { + return + } + output.WriteDebug("Download request failed: %s\n", err) + lastErr.Store(&err) + if !pauseBeforeRetry(ctx) { + return } } @@ -488,6 +514,9 @@ func (s *Server) Download(silent bool, useBytes, useMebi bool, requests int, chu // not a terminal defer func() { pb.Stop() + if failed { + return + } if useBytes { output.WriteUI("Download rate:\t%s\n", counter.AvgHumanize()) } else { @@ -521,10 +550,10 @@ Loop: // result doesn't change under us while it's being reported wg.Wait() - // No request got a response: whatever went out is not a measurement of - // 0 Mbps, it is a broken path. A request that ran into the client - // timeout with a response in hand counts as a result. + // No request answered with data is not a result of 0 Mbps. Without an + // error either, they were all still waiting when the test ended. if !succeeded.Load() { + failed = true if err := lastErr.Load(); err != nil { return 0, 0, *err } @@ -566,21 +595,33 @@ func (s *Server) Upload(noPrealloc, silent, useBytes, useMebi bool, requests int uploadDone := make(chan int, requests) var wg sync.WaitGroup - // the last error of a failed request, returned when no request got an - // answer, so a broken path is not reported as a 0 Mbps result - var lastErr atomic.Pointer[error] - var answered atomic.Bool + // whether any request was accepted, whether one without an answer had + // at least been sending for a while, and the last refusal and the last + // other failure + var succeeded, carried atomic.Bool + var refusedWith, lastErr atomic.Pointer[error] + var failed bool + + // The client follows a POST answered with 301, 302 or 303 as a GET + // without the payload, and the answer to that GET would count as an + // accepted upload. An upload is not sent on: a redirect is its answer. + client := *http.DefaultClient + client.CheckRedirect = func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + } doUpload := func(worker int) { defer wg.Done() var bodyReader io.Reader + sent := &sentBytes{total: counter} if noPrealloc { bodyReader = &SeekWrapper{rand.Reader} } else { bodyReader = bytes.NewReader(counter.Payload()) + sent.size = uint64(len(counter.Payload())) } - countingReader := io.TeeReader(bodyReader, counter) + countingReader := io.TeeReader(bodyReader, sent) uploadReq, err := http.NewRequestWithContext(WithWorker(ctx, worker), http.MethodPost, u.String(), countingReader) if err != nil { @@ -604,39 +645,74 @@ func (s *Server) Upload(noPrealloc, silent, useBytes, useMebi bool, requests int uploadReq.ContentLength = int64(len(counter.Payload())) } - resp, err := http.DefaultClient.Do(uploadReq) - if err != nil { - if ctx.Err() != nil { - // cancellation is how the test ends, so it is not a failure - return - } - output.WriteDebug("Failed when making HTTP request: %s\n", err) - lastErr.Store(&err) - // The body cannot be replayed, so the transport does not retry - // it. Let the main loop start a new request instead, after a - // pause so a refused connection does not spin. In auto mode a - // failed HTTP/3 request has already moved the server to TCP, so - // the new request goes over TCP. The bytes this one sent stay - // counted: with --no-pre-allocate the body never ends, every - // request ends at --timeout, and the server got all of them. - select { - case <-time.After(uploadRetryDelay): - case <-ctx.Done(): - return - } - select { - case uploadDone <- worker: - case <-ctx.Done(): - } + resp, err := client.Do(uploadReq) + // A request that was not accepted has still carried data when it + // had been sending for a while, however it ended: with the test, at + // the client timeout or on a dropped connection. A body that never + // ends can also be cut by the server, with the status a server sends + // once it has read as much as it takes. Any other error status is a + // refusal, however long the request took to get it. + timedOut := resp == nil && ctx.Err() == nil && errors.Is(err, context.DeadlineExceeded) + cut := noPrealloc && resp != nil && resp.StatusCode == http.StatusRequestEntityTooLarge && sent.started() + streamed := cut || (resp == nil && sent.sending(timedOut)) + if streamed { + carried.Store(true) + } + if err != nil && ctx.Err() != nil { + // cancellation is how the test ends, so it is not a failure return } - defer resp.Body.Close() - answered.Store(true) - if _, err := io.Copy(io.Discard, resp.Body); err != nil { - // cancellation is how the test ends, so it is not a failure - if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - output.WriteDebug("Failed when reading HTTP response: %s\n", err) + if resp != nil { + // A request is accepted once the server answers it with success: + // it has the payload then, whatever becomes of the rest of its + // answer. + if err = refusal("upload", resp); err == nil { + succeeded.Store(true) + if _, err := io.Copy(io.Discard, resp.Body); err != nil { + // cancellation is how the test ends, so it is not a failure + if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { + output.WriteDebug("Failed when reading HTTP response: %s\n", err) + } + } + } + // closed before the pause below, not after it + resp.Body.Close() + } + + // The client timeout cuts a request off while it is sending on a + // slow uplink, and with --no-pre-allocate where the body never + // ends. Such a request has not failed, and the next one follows it + // at once. Any other error is a failure. + if err != nil && !(streamed && timedOut) { + output.WriteDebug("Upload request failed: %s\n", err) + switch { + case streamed: + // what was sent before the request was cut stays counted + lastErr.Store(&err) + case resp != nil: + // what a refused request sent stays counted as well: it + // did cross the link + refusedWith.Store(&err) + case timedOut: + // The client timeout ended a request that had handed its + // payload over at once, or that sent nothing. What it sent + // may still be on its way, so it stays counted. + lastErr.Store(&err) + default: + // A connection that is dropped at once took in no more + // than the buffers on the way hold. Dropped requests are + // replaced several times a second, and that would add up. + lastErr.Store(&err) + sent.discount() + } + // The body cannot be sent again, so the transport does not + // retry a failed request. The main loop starts a new one + // instead, after a pause. In auto mode a failed HTTP/3 request + // has already moved the server to TCP, so the new request goes + // over TCP. + if !pauseBeforeRetry(ctx) { + return } } @@ -671,6 +747,9 @@ func (s *Server) Upload(noPrealloc, silent, useBytes, useMebi bool, requests int // not a terminal defer func() { pb.Stop() + if failed { + return + } if useBytes { output.WriteUI("Upload rate:\t%s\n", counter.AvgHumanize()) } else { @@ -704,24 +783,100 @@ Loop: // result doesn't change under us while it's being reported wg.Wait() - // A request that ran into the client timeout was still sending, as with - // --no-pre-allocate where the body never ends, so its bytes count as a - // result. Nothing answered and nothing was sent is not a result of 0 Mbps. - if !answered.Load() && counter.Total() == 0 { - if err := lastErr.Load(); err != nil { + // No accepted request is a failure when the server refused one: that is + // the only answer it gave. Without any answer the upload can still be a + // measurement. On a slow uplink no payload gets through before the + // client timeout or the end of the test cuts its request off, and with + // --no-pre-allocate the body never ends. What was sent is reported + // then, as it always was, as long as some request had been sending for + // a while. + // + // A server that takes the payload and never answers can look like a + // slow uplink from here, where the buffers on the way hold the payload. + // It is told apart only where the payload was handed over at once. + if !succeeded.Load() { + if err := refusedWith.Load(); err != nil { + failed = true return 0, 0, *err } - return 0, 0, errors.New("no upload request was answered before the test ended") - } - if err := lastErr.Load(); err != nil && !answered.Load() && !isTimeout(*err) { - return 0, 0, *err + if !carried.Load() { + failed = true + if err := lastErr.Load(); err != nil { + return 0, 0, *err + } + return 0, 0, errors.New("no upload request was answered before the test ended") + } } return counter.AvgMbps(), counter.Total(), nil } -func isTimeout(err error) bool { - var netErr net.Error - return errors.As(err, &netErr) && netErr.Timeout() +// sendingProof is how long ago a request has to have sent its first byte +// before what it sent stands as a measurement without an answer. A +// connection that is dropped at once does not get that far. +const sendingProof = 250 * time.Millisecond + +// sentBytes counts what one upload request sends, next to the counter of +// the whole test, and keeps the time of its first byte and of the last byte +// of its payload. The client may still read the body after it has returned, +// so everything is locked. +type sentBytes struct { + total *BytesCounter + // the length of the payload, zero for a body that never ends + size uint64 + + mu sync.Mutex + n uint64 + first time.Time + whole time.Time + gone bool +} + +func (s *sentBytes) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.gone { + return len(p), nil + } + if s.first.IsZero() { + s.first = time.Now() + } + s.n += uint64(len(p)) + if s.size > 0 && s.n >= s.size && s.whole.IsZero() { + s.whole = time.Now() + } + return s.total.Write(p) +} + +// started reports whether the request has sent anything. +func (s *sentBytes) started() bool { + s.mu.Lock() + defer s.mu.Unlock() + return !s.first.IsZero() +} + +// sending reports whether the request has been sending: for sendingProof +// since its first byte, or for any time at all when it is known to have +// lasted, as one does that the client timeout cut off. A payload that was +// handed over whole within sendingProof is not being sent any more. The +// buffers on the way took it in, or the server did, and the request has +// only waited for its answer since. +func (s *sentBytes) sending(lasted bool) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.first.IsZero() || (!lasted && time.Since(s.first) < sendingProof) { + return false + } + return s.whole.IsZero() || s.whole.Sub(s.first) >= sendingProof +} + +// discount takes what the request has sent back out of the count of the +// test, and keeps out what it may still send. +func (s *sentBytes) discount() { + s.mu.Lock() + defer s.mu.Unlock() + s.gone = true + s.total.Discount(s.n) + s.n = 0 } // downloadReadSize is how much each download read asks for. On loopback, @@ -730,8 +885,44 @@ func isTimeout(err error) bool { // HTTP/2 client, so the server is never left waiting for window. const downloadReadSize = 256 << 10 -// uploadRetryDelay spaces the retries of failed upload requests. -const uploadRetryDelay = 200 * time.Millisecond +// retryDelay spaces the requests that follow a failed one, so that a wrong +// URL is not asked for as fast as the server can refuse it. +const retryDelay = 200 * time.Millisecond + +// errorPageLimit is how much of a refused answer is read before it is closed. +const errorPageLimit = 4 << 10 + +// refusal reports a transfer request that was not answered with success. +// Any 2xx status is success. Everything else comes with an error page or +// nothing, not with test data, and that includes a redirect the client did +// not follow. +// +// A short error page is read to its end, so that the retry can use the +// connection again and does not open a new one each time. Only newer Go +// versions do that on their own. A page that does not say how long it is +// is left alone: reading it could wait for a server that never ends it. +func refusal(phase string, resp *http.Response) error { + if resp.StatusCode >= 200 && resp.StatusCode <= 299 { + return nil + } + if n := resp.ContentLength; n > 0 && n <= errorPageLimit { + io.CopyN(io.Discard, resp.Body, n) + } + if text := http.StatusText(resp.StatusCode); text != "" { + return fmt.Errorf("the %s request returned HTTP %d %s", phase, resp.StatusCode, text) + } + return fmt.Errorf("the %s request returned HTTP %d", phase, resp.StatusCode) +} + +// pauseBeforeRetry waits retryDelay and reports whether the test is still on. +func pauseBeforeRetry(ctx context.Context) bool { + select { + case <-time.After(retryDelay): + return true + case <-ctx.Done(): + return false + } +} // GetIPInfo accesses the backend's getIP.php endpoint and get current client's IP information func (s *Server) GetIPInfo(distanceUnit string) (*GetIPResult, error) { diff --git a/defs/transfer_status_test.go b/defs/transfer_status_test.go new file mode 100644 index 0000000..93abdbd --- /dev/null +++ b/defs/transfer_status_test.go @@ -0,0 +1,829 @@ +package defs + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" +) + +// refusingServer answers every transfer request with an error page and +// counts the requests. +func refusingServer(t *testing.T, status int) (*Server, *atomic.Int64) { + t.Helper() + + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + io.Copy(io.Discard, r.Body) + w.WriteHeader(status) + w.Write([]byte(strings.Repeat("
this is an error page
\n", 100))) + })) + t.Cleanup(ts.Close) + + return &Server{Server: ts.URL, DownloadURL: "garbage.php", UploadURL: "empty.php"}, &requests +} + +// A download URL that answers 404 gives nothing to measure. The test must +// fail with the status instead of timing the error pages, and must not ask +// again as fast as the server can refuse. +func TestDownloadFailsWhenEveryRequestIsRefused(t *testing.T) { + s, requests := refusingServer(t, http.StatusNotFound) + + _, total, err := s.Download(true, false, false, 2, 1, time.Second) + + if err == nil || err.Error() != "the download request returned HTTP 404 Not Found" { + t.Errorf("error = %v, want the 404 named", err) + } + if total != 0 { + t.Errorf("counted %d bytes of error pages as downloaded", total) + } + if n := requests.Load(); n > 50 { + t.Errorf("%d requests in a second, want a pause between refused ones", n) + } +} + +func TestUploadFailsWhenEveryRequestIsRefused(t *testing.T) { + s, requests := refusingServer(t, http.StatusRequestEntityTooLarge) + + _, _, err := s.Upload(false, true, false, false, 2, 16, time.Second) + + if err == nil || err.Error() != "the upload request returned HTTP 413 Request Entity Too Large" { + t.Errorf("error = %v, want the 413 named", err) + } + if n := requests.Load(); n > 50 { + t.Errorf("%d requests in a second, want a pause between refused ones", n) + } +} + +// A refused request is asked again after a pause. The retries must not each +// open a connection of their own: a short error page that says how long it +// is gets read, so the connection it came over can be used again. +func TestRefusedRequestsKeepTheirConnections(t *testing.T) { + const streams = 2 + + for _, phase := range []string{"download", "upload"} { + t.Run(phase, func(t *testing.T) { + var requests, connections atomic.Int64 + page := strings.Repeat("this is an error page
\n", 100) + ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Length", strconv.Itoa(len(page))) + w.WriteHeader(http.StatusNotFound) + w.Write([]byte(page)) + })) + ts.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateNew { + connections.Add(1) + } + } + ts.Start() + defer ts.Close() + + s := &Server{Server: ts.URL, DownloadURL: "garbage.php", UploadURL: "empty.php"} + if phase == "download" { + s.Download(true, false, false, streams, 1, time.Second) + } else { + s.Upload(false, true, false, false, streams, 16, time.Second) + } + + // one more than the streams leaves room for a connection that + // was being opened when another one became free + if r, c := requests.Load(), connections.Load(); r <= streams+1 || c > streams+1 { + t.Errorf("%d requests over %d connections, want the %d streams to keep theirs", r, c, streams) + } + }) + } +} + +// One refused request among good ones does not fail the test, and its error +// page is not counted as data. +func TestDownloadDoesNotCountAnErrorPage(t *testing.T) { + const data = "0123456789" + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if requests.Add(1) == 1 { + w.WriteHeader(http.StatusServiceUnavailable) + // a length the data cannot add up to + w.Write([]byte(strings.Repeat("x", 4096+3))) + return + } + w.Write([]byte(data)) + })) + defer ts.Close() + + s := &Server{Server: ts.URL, DownloadURL: "garbage.php"} + _, total, err := s.Download(true, false, false, 1, 1, time.Second) + + if err != nil { + t.Fatalf("Download: %v", err) + } + if total == 0 || total%uint64(len(data)) != 0 { + t.Errorf("counted %d bytes, want only whole %d-byte answers", total, len(data)) + } +} + +// A download URL whose connections are dropped gives nothing to measure +// either. The test fails with the cause instead of reporting 0 Mbps. +func TestDownloadFailsWhenEveryRequestIsDropped(t *testing.T) { + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + conn.(*net.TCPConn).SetLinger(0) + conn.Close() + })) + defer ts.Close() + + s := &Server{Server: ts.URL, DownloadURL: "garbage.php"} + _, total, err := s.Download(true, false, false, 2, 1, time.Second) + + if err == nil { + t.Error("no error, want the dropped connection reported") + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } + if n := requests.Load(); n > 50 { + t.Errorf("%d requests in a second, want a pause between failed ones", n) + } +} + +// A download whose answers are cut short is a result all the same: what +// arrived did cross the link. On a slow link the end of the test cuts every +// request, and none ever gets its whole body. +func TestDownloadCountsAnswersThatAreCutShort(t *testing.T) { + chunk := make([]byte, 16<<10) + + for _, tc := range []struct { + name string + send http.HandlerFunc + }{ + {"by the end of the test", func(w http.ResponseWriter, r *http.Request) { + for r.Context().Err() == nil { + w.Write(chunk) + w.(http.Flusher).Flush() + time.Sleep(20 * time.Millisecond) + } + }}, + {"by the server", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1048576") + w.Write(chunk) + w.(http.Flusher).Flush() + // each aborted answer costs a connection, so they are spaced + time.Sleep(5 * time.Millisecond) + panic(http.ErrAbortHandler) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + ts := httptest.NewServer(tc.send) + defer ts.Close() + + s := &Server{Server: ts.URL, DownloadURL: "garbage.php"} + _, total, err := s.Download(true, false, false, 2, 1, 500*time.Millisecond) + + if err != nil { + t.Errorf("Download returned error: %v", err) + } + if total == 0 { + t.Error("nothing was counted") + } + }) + } +} + +// An upload is accepted once the server answers it with success. The server +// has the payload then, so an answer that is cut short after that does not +// make the request a failed one. +func TestUploadCountsARequestWhoseAnswerIsCutShort(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Length", "100") + w.Write([]byte("ok")) + w.(http.Flusher).Flush() + // each aborted answer costs a connection, so they are spaced + time.Sleep(5 * time.Millisecond) + panic(http.ErrAbortHandler) + })) + defer ts.Close() + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 2, 16, 500*time.Millisecond) + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if total == 0 { + t.Error("nothing was counted") + } +} + +// A download URL that answers with success and no body has nothing to +// measure either, and is not asked again without a pause. +func TestDownloadFailsWhenTheAnswersAreEmpty(t *testing.T) { + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + })) + defer ts.Close() + + s := &Server{Server: ts.URL, DownloadURL: "garbage.php"} + _, total, err := s.Download(true, false, false, 2, 1, time.Second) + + if err == nil || err.Error() != "the download request returned no data" { + t.Errorf("error = %v, want the empty answers reported", err) + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } + if n := requests.Load(); n > 50 { + t.Errorf("%d requests in a second, want a pause between empty ones", n) + } +} + +// clientTimeout sets the timeout of the HTTP client for one test. +func clientTimeout(t *testing.T, d time.Duration) { + t.Helper() + old := http.DefaultClient.Timeout + http.DefaultClient.Timeout = d + t.Cleanup(func() { http.DefaultClient.Timeout = old }) +} + +// An upload URL that nothing listens on gives nothing to measure. The test +// fails with the cause instead of reporting 0 Mbps. +func TestUploadFailsWhenNoRequestReachesTheServer(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + l.Close() + + s := &Server{Server: "http://" + addr, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 2, 16, time.Second) + + if err == nil { + t.Error("no error, want the refused connection reported") + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } +} + +// An upload URL whose connections are dropped fails the same way. The +// client cannot send a body twice, so each dropped request is replaced by a +// new one, after a pause. +func TestUploadFailsWhenEveryRequestIsDropped(t *testing.T) { + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + conn.(*net.TCPConn).SetLinger(0) + conn.Close() + })) + defer ts.Close() + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, _, err := s.Upload(false, true, false, false, 2, 16, time.Second) + + if err == nil { + t.Error("no error, want the dropped connection reported") + } + if n := requests.Load(); n <= 2 || n > 50 { + t.Errorf("%d requests in a second, want the dropped ones replaced after a pause", n) + } +} + +// The time a request takes to connect is not time spent sending. A slow +// connect in front of the dropped connections does not make them a +// measurement. +func TestUploadFailsWhenEveryRequestIsDroppedAfterASlowConnect(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + conn.(*net.TCPConn).SetLinger(0) + conn.Close() + })) + defer ts.Close() + + old := http.DefaultClient.Transport + http.DefaultClient.Transport = &http.Transport{ + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + select { + case <-time.After(1200 * time.Millisecond): + case <-ctx.Done(): + return nil, ctx.Err() + } + return (&net.Dialer{}).DialContext(ctx, network, addr) + }, + } + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, _, err := s.Upload(false, true, false, false, 1, 16, 2*time.Second) + + if err == nil { + t.Error("no error, want the dropped connection reported") + } +} + +// neverSends stands for an address that swallows connection attempts: no +// request sent through it gets as far as sending anything. +type neverSends struct{} + +func (neverSends) RoundTrip(req *http.Request) (*http.Response, error) { + <-req.Context().Done() + return nil, req.Context().Err() +} + +// An upload that sent nothing at all is not a result of 0 Mbps, whether its +// requests ran into the client timeout or were still waiting when the test +// ended. +func TestUploadFailsWhenNothingIsSent(t *testing.T) { + for name, timeout := range map[string]time.Duration{ + "the requests time out": 200 * time.Millisecond, + "the test ends first": 5 * time.Second, + } { + t.Run(name, func(t *testing.T) { + clientTimeout(t, timeout) + old := http.DefaultClient.Transport + http.DefaultClient.Transport = neverSends{} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + s := &Server{Server: "http://127.0.0.1:1", UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 2, 16, time.Second) + + if err == nil { + t.Error("no error, want the missing answers reported") + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } + }) + } +} + +// slowConn is a connection that sends 4 KiB per pause, the way a slow +// uplink does: what is written to it gets through a little at a time. +type slowConn struct { + net.Conn + pause time.Duration +} + +func (c slowConn) Write(p []byte) (int, error) { + for sent := 0; sent < len(p); { + n, err := c.Conn.Write(p[sent:min(sent+4<<10, len(p))]) + sent += n + if err != nil { + return sent, err + } + time.Sleep(c.pause) + } + return len(p), nil +} + +// slowUplink sends the requests of one test over slowConn. +func slowUplink(t *testing.T, pause time.Duration) { + t.Helper() + old := http.DefaultClient.Transport + http.DefaultClient.Transport = &http.Transport{ + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := (&net.Dialer{}).DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + return slowConn{conn, pause}, nil + }, + } + t.Cleanup(func() { http.DefaultClient.Transport = old }) +} + +// On a slow uplink no payload gets through before the test or the client +// timeout cuts its request off, so no request is ever answered. What was +// sent is the measurement all the same. +func TestUploadCountsWhatASlowUplinkSent(t *testing.T) { + for name, timeout := range map[string]time.Duration{ + "the requests time out": 1100 * time.Millisecond, + "the test ends first": 5 * time.Second, + } { + t.Run(name, func(t *testing.T) { + clientTimeout(t, timeout) + // about 200 KiB/s + slowUplink(t, 20*time.Millisecond) + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + })) + defer ts.Close() + + // a payload that takes far longer than the test + const payload = 32 << 20 + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 2, payload>>10, 1500*time.Millisecond) + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if total == 0 || total >= 2*payload { + t.Errorf("counted %d bytes, want a part of the two payloads", total) + } + }) + } +} + +// An upload URL that takes the payload and never answers leaves nothing to +// measure. A payload that was handed over at once is not being sent any +// more: the request only waits, to the end of the test or to the client +// timeout. That is a failure, even though the bytes did go out. +func TestUploadFailsWhenThePayloadIsTakenAndNotAnswered(t *testing.T) { + for name, timeout := range map[string]time.Duration{ + "the requests time out": 400 * time.Millisecond, + "the test ends first": 5 * time.Second, + } { + t.Run(name, func(t *testing.T) { + clientTimeout(t, timeout) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + <-r.Context().Done() + })) + defer ts.Close() + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 1, 16, time.Second) + + if err == nil { + t.Error("no error, want the missing answers reported") + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } + }) + } +} + +// Such a payload is not thrown away, though, when another stream is still +// sending. It may as well sit in the buffers of a slow uplink, and the +// stream that is still sending makes the upload a measurement. +func TestUploadKeepsAHandedOverPayloadBesideAStreamThatSends(t *testing.T) { + clientTimeout(t, time.Second) + // handed over well within sendingProof + const payload = 4 << 20 + + // The first connection is fast. The others send about 200 KiB/s, so + // they are still sending at the end and add far less than a payload. + var dials atomic.Int64 + old := http.DefaultClient.Transport + http.DefaultClient.Transport = &http.Transport{ + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := (&net.Dialer{}).DialContext(ctx, network, addr) + if err != nil || dials.Add(1) == 1 { + return conn, err + } + return slowConn{conn, 20 * time.Millisecond}, nil + }, + } + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + var requests atomic.Int64 + done := make(chan struct{}) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + if requests.Add(1) == 1 { + // the first payload is taken and never answered + select { + case <-done: + case <-r.Context().Done(): + } + } + })) + defer ts.Close() + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 2, payload>>10, 2*time.Second) + close(done) + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if total < payload { + t.Errorf("counted %d bytes, want the %d of the payload that timed out kept", total, payload) + } +} + +// With --no-pre-allocate the body never ends, so no request is ever answered +// either, and the server still got what was sent. +func TestUploadCountsAStreamThatNeverEnds(t *testing.T) { + for name, timeout := range map[string]time.Duration{ + "the requests time out": 1100 * time.Millisecond, + "the test ends first": 5 * time.Second, + } { + t.Run(name, func(t *testing.T) { + clientTimeout(t, timeout) + var received atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n, _ := io.Copy(io.Discard, r.Body) + received.Add(n) + })) + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(true, true, false, false, 2, 16, 1500*time.Millisecond) + // the server has counted every request once it is closed + ts.Close() + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + // the count runs ahead of the server by what is on the way + if got := uint64(received.Load()); got == 0 || got < total/2 { + t.Errorf("counted %d bytes while the server received %d", total, got) + } + }) + } +} + +// cuttingServer takes the body of each request for half a second and then +// answers with the given status. It counts the requests and what it read. +func cuttingServer(t *testing.T, status int) (*Server, *atomic.Int64, *atomic.Int64) { + t.Helper() + + var requests, received atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + buf := make([]byte, 64<<10) + for end := time.Now().Add(500 * time.Millisecond); time.Now().Before(end); { + n, err := r.Body.Read(buf) + received.Add(int64(n)) + if err != nil { + break + } + } + w.WriteHeader(status) + })) + t.Cleanup(ts.Close) + + return &Server{Server: ts.URL, UploadURL: "empty.php"}, &requests, &received +} + +// A server may cut such a body off once it gets too large for it, with the +// status for that. The stream had been sending until then, so what it sent +// is a measurement, and the next request follows. +func TestUploadCountsAStreamThatTheServerCuts(t *testing.T) { + clientTimeout(t, 5*time.Second) + s, requests, received := cuttingServer(t, http.StatusRequestEntityTooLarge) + + _, total, err := s.Upload(true, true, false, false, 2, 16, 1500*time.Millisecond) + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if got := uint64(received.Load()); got == 0 || got < total/2 { + t.Errorf("counted %d bytes while the server received %d", total, got) + } + if n := requests.Load(); n <= 2 { + t.Errorf("%d requests, want the cut ones replaced", n) + } +} + +// Any other error status is a refusal for a stream as well, whether it +// comes after a while or at once. +func TestUploadFailsWhenAStreamIsRefusedLate(t *testing.T) { + clientTimeout(t, 5*time.Second) + s, _, _ := cuttingServer(t, http.StatusInternalServerError) + + _, total, err := s.Upload(true, true, false, false, 2, 16, 1500*time.Millisecond) + + if err == nil || err.Error() != "the upload request returned HTTP 500 Internal Server Error" { + t.Errorf("error = %v, want the refusal reported", err) + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } +} + +// The status for a body that got too large shows that the server read the +// stream, also when it comes at once. +func TestUploadCountsAStreamThatTheServerCutsAtOnce(t *testing.T) { + var received atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n, _ := io.CopyN(io.Discard, r.Body, 4<<20) + received.Add(n) + w.WriteHeader(http.StatusRequestEntityTooLarge) + })) + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(true, true, false, false, 1, 16, time.Second) + ts.Close() + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if got := uint64(received.Load()); total == 0 || got < total/2 { + t.Errorf("counted %d bytes while the server received %d", total, got) + } +} + +func TestUploadFailsWhenAStreamIsRefusedAtOnce(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + defer ts.Close() + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(true, true, false, false, 2, 16, time.Second) + + if err == nil || err.Error() != "the upload request returned HTTP 404 Not Found" { + t.Errorf("error = %v, want the refusal reported", err) + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } +} + +// One dropped connection does not spoil such an upload. No request of it is +// ever accepted, and the others had been sending all along. +func TestUploadCountsWhatWasSentBesideADroppedRequest(t *testing.T) { + clientTimeout(t, 5*time.Second) + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if requests.Add(1) == 2 { + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + conn.(*net.TCPConn).SetLinger(0) + conn.Close() + return + } + io.Copy(io.Discard, r.Body) + })) + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(true, true, false, false, 2, 16, 1500*time.Millisecond) + ts.Close() + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if total == 0 { + t.Error("nothing was counted") + } + if n := requests.Load(); n < 3 { + t.Errorf("%d requests, want the dropped one replaced", n) + } +} + +// Neither does a connection that is dropped after it had carried data for a +// while, even when nothing gets through after it. A server that ends a long +// body this way did take what was sent before. +func TestUploadCountsARequestThatWasDroppedWhileSending(t *testing.T) { + clientTimeout(t, 5*time.Second) + var requests atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if requests.Add(1) == 1 { + // taken for longer than a connection dropped at once lives, + // and dropped well before the test ends + buf := make([]byte, 64<<10) + for end := time.Now().Add(1200 * time.Millisecond); time.Now().Before(end); { + if _, err := r.Body.Read(buf); err != nil { + break + } + } + } + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + conn.(*net.TCPConn).SetLinger(0) + conn.Close() + })) + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(true, true, false, false, 1, 16, 2*time.Second) + ts.Close() + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + if total == 0 { + t.Error("nothing was counted") + } + if n := requests.Load(); n < 2 { + t.Errorf("%d requests, want the dropped one replaced", n) + } +} + +// A refusal stays a refusal however long the request took to get it. +func TestUploadFailsWhenEveryRequestIsRefusedLate(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + time.Sleep(1200 * time.Millisecond) + w.WriteHeader(http.StatusInternalServerError) + })) + defer ts.Close() + + // the test ends while a request has been waiting for a second + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 1, 16, 2300*time.Millisecond) + + if err == nil || err.Error() != "the upload request returned HTTP 500 Internal Server Error" { + t.Errorf("error = %v, want the refusal reported", err) + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } +} + +// What a dropped request had sent is not part of the result. Dropped +// requests are replaced several times a second, and each one would add what +// fit into the buffers on the way. +func TestUploadDoesNotCountDroppedRequests(t *testing.T) { + const payload = 16 << 10 + var requests, accepted atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if requests.Add(1)%2 == 0 { + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + conn.(*net.TCPConn).SetLinger(0) + conn.Close() + return + } + io.Copy(io.Discard, r.Body) + // slow enough for the dropped requests to weigh in the total + time.Sleep(100 * time.Millisecond) + accepted.Add(1) + })) + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 2, payload>>10, 2*time.Second) + ts.Close() + + if err != nil { + t.Errorf("Upload returned error: %v", err) + } + // the requests that were cut off by the end of the test count as well + if most := uint64(accepted.Load()+2) * payload; total == 0 || total > most { + t.Errorf("counted %d bytes, want no more than the %d of the accepted requests", total, most) + } + if n := requests.Load() - accepted.Load(); n < 3 { + t.Errorf("%d dropped requests, too few to tell", n) + } +} + +// An upload is not sent on to where a redirect points. The client would +// follow a 301, 302 or 303 as a GET without the payload, and the answer to +// that GET is no upload. A redirect is a refusal like any other answer that +// is not a success. +func TestUploadDoesNotFollowARedirect(t *testing.T) { + for _, status := range []int{http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther} { + t.Run(strconv.Itoa(status), func(t *testing.T) { + var followed atomic.Int64 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + followed.Add(1) + })) + defer target.Close() + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + http.Redirect(w, r, target.URL+r.URL.RequestURI(), status) + })) + defer ts.Close() + + s := &Server{Server: ts.URL, UploadURL: "empty.php"} + _, total, err := s.Upload(false, true, false, false, 1, 16, time.Second) + + want := fmt.Sprintf("the upload request returned HTTP %d %s", status, http.StatusText(status)) + if err == nil || err.Error() != want { + t.Errorf("error = %v, want %q", err, want) + } + if total != 0 { + t.Errorf("counted %d bytes", total) + } + if n := followed.Load(); n != 0 { + t.Errorf("%d requests went on to the redirect target, want none", n) + } + }) + } +} diff --git a/secure_redirect_test.go b/secure_redirect_test.go new file mode 100644 index 0000000..c40bb96 --- /dev/null +++ b/secure_redirect_test.go @@ -0,0 +1,186 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync/atomic" + "testing" +) + +// redirectingFront is an HTTPS server that sends the requests for the given +// paths on to a plain HTTP backend, and answers the others itself. +func redirectingFront(t *testing.T, backend *httptest.Server, paths ...string) *httptest.Server { + t.Helper() + + front := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for _, path := range paths { + if r.URL.Path == path { + http.Redirect(w, r, backend.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) + return + } + } + if r.URL.Path == "/getIP.php" { + w.Write([]byte(`{"processedString":"127.0.0.1 - localhost","rawIspInfo":""}`)) + } + })) + t.Cleanup(front.Close) + return front +} + +const refusedRedirect = "the server redirected to plain HTTP, which --secure does not allow" + +// --secure asks for HTTPS to every test server. A server that answers with a +// redirect to plain HTTP must not move the test there. +func TestSecureRefusesARedirectToPlainHTTP(t *testing.T) { + var overPlainHTTP atomic.Int64 + plain := transferBackend(t, http.StatusOK) + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + overPlainHTTP.Add(1) + plain.Config.Handler.ServeHTTP(w, r) + })) + t.Cleanup(backend.Close) + front := redirectingFront(t, backend, "/empty.php", "/getIP.php", "/garbage.php") + + list := writeServerList(t, listedServer{1, "Front", front.URL, "empty.php"}) + args := []string{"--local-json", list, "--server", "1", "--skip-cert-verify", + "--duration", "1", "--no-icmp", "--no-download", "--no-upload", "--json"} + + // without --secure the redirect is followed, as it always was + if r := runCLI(t, args...); r.code != 0 || overPlainHTTP.Load() == 0 { + t.Errorf("without --secure: exit status %d and %d requests over plain HTTP, want 0 and some, stderr:\n%s", r.code, overPlainHTTP.Load(), r.stderr) + } + + overPlainHTTP.Store(0) + r := runCLI(t, append(args, "--secure")...) + if r.code != 1 { + t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr) + } + if r.stdout != "" { + t.Errorf("stdout = %q, want no report", r.stdout) + } + if msg := r.failure(t); !strings.HasSuffix(msg, refusedRedirect) { + t.Errorf("error = %q, want it to end in %q", msg, refusedRedirect) + } + if n := overPlainHTTP.Load(); n != 0 { + t.Errorf("%d requests went on over plain HTTP, want none", n) + } +} + +// The same holds when only the download URL is redirected: the download is +// neither measured over plain HTTP nor reported as 0 Mbps. +func TestSecureRefusesARedirectedDownload(t *testing.T) { + backend := transferBackend(t, http.StatusOK) + front := redirectingFront(t, backend, "/garbage.php") + + list := writeServerList(t, listedServer{1, "Front", front.URL, "empty.php"}) + r := runCLI(t, "--local-json", list, "--server", "1", "--skip-cert-verify", "--secure", + "--duration", "1", "--no-icmp", "--no-upload", "--json") + + if r.code != 1 { + t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr) + } + if r.stdout != "" { + t.Errorf("stdout = %q, want no report", r.stdout) + } + if msg := r.failure(t); !strings.HasSuffix(msg, refusedRedirect) { + t.Errorf("error = %q, want it to end in %q", msg, refusedRedirect) + } +} + +// And when only the upload is redirected. An upload does not follow a +// redirect, so a 302 and a 307 both arrive as a status. Neither is a +// result, and neither sends anything on over plain HTTP. +func TestSecureRefusesARedirectedUpload(t *testing.T) { + for _, tc := range []struct { + status int + want string + }{ + {http.StatusFound, "the upload request returned HTTP 302 Found"}, + {http.StatusTemporaryRedirect, "the upload request returned HTTP 307 Temporary Redirect"}, + } { + t.Run(strconv.Itoa(tc.status), func(t *testing.T) { + var overPlainHTTP atomic.Int64 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + overPlainHTTP.Add(1) + })) + t.Cleanup(backend.Close) + + front := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost: + http.Redirect(w, r, backend.URL+r.URL.RequestURI(), tc.status) + case r.URL.Path == "/getIP.php": + w.Write([]byte(`{"processedString":"127.0.0.1 - localhost","rawIspInfo":""}`)) + } + })) + t.Cleanup(front.Close) + + list := writeServerList(t, listedServer{1, "Front", front.URL, "empty.php"}) + // the payload is small enough for the server to take in whole, so + // that it has no unread body to close the connection on + r := runCLI(t, "--local-json", list, "--server", "1", "--skip-cert-verify", "--secure", + "--duration", "1", "--no-icmp", "--no-download", "--upload-size", "16", "--json") + + if r.code != 1 { + t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr) + } + if r.stdout != "" { + t.Errorf("stdout = %q, want no report", r.stdout) + } + if msg := r.failure(t); !strings.HasSuffix(msg, tc.want) { + t.Errorf("error = %q, want it to end in %q", msg, tc.want) + } + if n := overPlainHTTP.Load(); n != 0 { + t.Errorf("%d requests went on over plain HTTP, want none", n) + } + }) + } +} + +// The telemetry request is made after the test, with a client of its own +// that gets the same policy, so --secure covers it as well. A telemetry +// server that sends the result on to plain HTTP gets an error line and the +// result stays off plain HTTP. The run itself has its result and is not +// failed by that. +func TestSecureRefusesARedirectedTelemetry(t *testing.T) { + var overPlainHTTP atomic.Int64 + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + overPlainHTTP.Add(1) + })) + t.Cleanup(plain.Close) + + telemetry := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, plain.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) + })) + t.Cleanup(telemetry.Close) + + // a test server that redirects nothing + front := redirectingFront(t, plain) + list := writeServerList(t, listedServer{1, "Front", front.URL, "empty.php"}) + args := []string{"--local-json", list, "--server", "1", "--skip-cert-verify", + "--duration", "1", "--no-icmp", "--no-download", "--no-upload", "--json", + "--telemetry-server", telemetry.URL} + + // without --secure the redirect is followed, as it always was + if r := runCLI(t, args...); r.code != 0 || overPlainHTTP.Load() == 0 { + t.Errorf("without --secure: exit status %d and %d requests over plain HTTP, want 0 and some, stderr:\n%s", + r.code, overPlainHTTP.Load(), r.stderr) + } + overPlainHTTP.Store(0) + + r := runCLI(t, append(args, "--secure")...) + if r.code != 0 { + t.Errorf("exit status %d, want 0, stderr:\n%s", r.code, r.stderr) + } + if !strings.Contains(r.stdout, `"name":"Front"`) { + t.Errorf("stdout = %q, want the report", r.stdout) + } + if !strings.Contains(r.stderr, "Error when sending telemetry data: ") || !strings.Contains(r.stderr, refusedRedirect) { + t.Errorf("stderr does not name the refused telemetry redirect:\n%s", r.stderr) + } + if n := overPlainHTTP.Load(); n != 0 { + t.Errorf("%d requests went on over plain HTTP, want none", n) + } +} diff --git a/speedtest/helper.go b/speedtest/helper.go index c68a1bb..28e7c9d 100644 --- a/speedtest/helper.go +++ b/speedtest/helper.go @@ -10,7 +10,9 @@ import ( "math" "mime/multipart" "net/http" + "net/url" "os" + "slices" "strconv" "strings" "time" @@ -51,9 +53,17 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel var reps_json []report.JSONReport var reps_csv []report.CSVReport var measured bool - // each server that did not answer its probe, and why + // each server that gave no result, and why: it did not answer its probe, + // or its download or upload test failed var down []downServer + // add a new line after each test if testing multiple servers + separate := func() { + if len(servers) > 1 && !silent { + output.WriteUIBlank() + } + } + // fetch current user's IP info for _, currentServer := range servers { // get telemetry level @@ -137,8 +147,13 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel download, br, err := currentServer.Download(silent, c.Bool(defs.OptionBytes), c.Bool(defs.OptionMebiBytes), c.Int(defs.OptionConcurrent), c.Int(defs.OptionChunks), time.Duration(c.Int(defs.OptionDuration))*time.Second) if err != nil { - output.WriteError("Failed to get download speed: %s\n", output.Sanitize(err.Error())) - return err + // with one server the error that ends the run says it + if len(servers) > 1 { + output.WriteError("Failed to get download speed: %s\n", output.Sanitize(err.Error())) + } + down = append(down, failedServer(currentServer, u, err, true)) + separate() + continue } downloadValue = download bytesRead = br @@ -159,8 +174,13 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel upload, bw, err := currentServer.Upload(c.Bool(defs.OptionNoPreAllocate), silent, c.Bool(defs.OptionBytes), c.Bool(defs.OptionMebiBytes), c.Int(defs.OptionConcurrent), c.Int(defs.OptionUploadSize), time.Duration(c.Int(defs.OptionDuration))*time.Second) if err != nil { - output.WriteError("Failed to get upload speed: %s\n", output.Sanitize(err.Error())) - return err + // with one server the error that ends the run says it + if len(servers) > 1 { + output.WriteError("Failed to get upload speed: %s\n", output.Sanitize(err.Error())) + } + down = append(down, failedServer(currentServer, u, err, true)) + separate() + continue } uploadValue = upload bytesWritten = bw @@ -267,20 +287,14 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel measured = true } else { output.WriteUI("Selected server %s (%s) is not responding at the moment, try again later\n", output.Sanitize(currentServer.Name), output.Sanitize(u.Hostname())) - down = append(down, downServer{ - server: fmt.Sprintf("%s (%s)", output.Sanitize(currentServer.Name), output.Sanitize(u.Hostname())), - reason: output.Sanitize(upErr.Error()), - }) + down = append(down, failedServer(currentServer, u, upErr, false)) } - //add a new line after each test if testing multiple servers - if len(servers) > 1 && !silent { - output.WriteUIBlank() - } + separate() } - // No server answered: fail instead of printing an empty report, which - // with exit status 0 would pass for a result. + // No server gave a result: fail instead of printing an empty report, + // which with exit status 0 would pass for a result. if !measured && len(down) > 0 { return noneResponding(down) } @@ -307,22 +321,44 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel return nil } -// downServer is a selected server that did not answer its probe. +// downServer is a selected server that gave no result. type downServer struct { server string // name and host, ready to print reason string + // answered tells a server that answered its probe and then failed its + // download or upload test from one that did not answer at all + answered bool +} + +// failedServer notes a server that gave no result, and why. +func failedServer(s defs.Server, u *url.URL, err error, answered bool) downServer { + return downServer{ + server: fmt.Sprintf("%s (%s)", output.Sanitize(s.Name), output.Sanitize(u.Hostname())), + reason: output.Sanitize(err.Error()), + answered: answered, + } } // noneResponding names every selected server with its cause. It is printed -// after "Terminated due to error: ", hence the capital letter. +// after "Terminated due to error: ", hence the capital letter. A server that +// answered its probe did respond, so with one of those among them the text +// speaks of results instead. func noneResponding(down []downServer) error { + answered := slices.ContainsFunc(down, func(d downServer) bool { return d.answered }) + if len(down) == 1 { + if answered { + return fmt.Errorf("Selected server %s gave no result: %s", down[0].server, down[0].reason) + } return fmt.Errorf("Selected server %s is not responding: %s", down[0].server, down[0].reason) } causes := make([]string, 0, len(down)) for _, d := range down { causes = append(causes, d.server+": "+d.reason) } + if answered { + return fmt.Errorf("None of the %d selected servers gave a result: %s", len(down), strings.Join(causes, "; ")) + } return fmt.Errorf("None of the %d selected servers is responding: %s", len(down), strings.Join(causes, "; ")) } diff --git a/speedtest/redirect_test.go b/speedtest/redirect_test.go new file mode 100644 index 0000000..513328e --- /dev/null +++ b/speedtest/redirect_test.go @@ -0,0 +1,47 @@ +package speedtest + +import ( + "net/http" + "net/url" + "testing" +) + +func TestRefuseDowngrade(t *testing.T) { + request := func(rawURL string) *http.Request { + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("parse %q: %v", rawURL, err) + } + return &http.Request{URL: u} + } + + cases := []struct { + name string + from string + to string + wantErr bool + }{ + {"HTTPS to HTTPS", "https://a.example/empty.php", "https://b.example/empty.php", false}, + {"HTTPS to plain HTTP", "https://a.example/empty.php", "http://a.example/empty.php", true}, + {"plain HTTP to plain HTTP", "http://a.example/telemetry", "http://b.example/telemetry", false}, + {"plain HTTP to HTTPS", "http://a.example/telemetry", "https://a.example/telemetry", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := refuseDowngrade(request(c.to), []*http.Request{request(c.from)}) + if (err != nil) != c.wantErr { + t.Errorf("error = %v, want an error: %t", err, c.wantErr) + } + }) + } + + t.Run("too many redirects", func(t *testing.T) { + via := make([]*http.Request, 10) + for i := range via { + via[i] = request("https://a.example/empty.php") + } + if err := refuseDowngrade(request("https://a.example/empty.php"), via); err == nil { + t.Error("followed an eleventh redirect") + } + }) +} diff --git a/speedtest/speedtest.go b/speedtest/speedtest.go index 01abea0..d206dfa 100644 --- a/speedtest/speedtest.go +++ b/speedtest/speedtest.go @@ -363,6 +363,22 @@ func SpeedTest(c *cli.Context) error { return nil } + // From here on the requests go to the test servers and, with telemetry + // on, to its server. Under --secure a redirect may not take any of them + // from HTTPS to plain HTTP. A telemetry server given with http:// is + // still used as given, and the server list was fetched the way its own + // URL says, which --secure leaves alone. + if forceScheme == forceHttps { + // undone when the run ends, so that the policy does not stay on + // the client the whole process shares + defer func(old func(*http.Request, []*http.Request) error) { + http.DefaultClient.CheckRedirect = old + }(http.DefaultClient.CheckRedirect) + http.DefaultClient.CheckRedirect = refuseDowngrade + // telemetry has a client of its own, made for this run + telemetryClient.CheckRedirect = refuseDowngrade + } + // if --server is given, do speed tests with all of them if len(c.IntSlice(defs.OptionServer)) > 0 { return doSpeedTest(c, servers, telemetryServer, network, silent, noICMP) @@ -473,6 +489,19 @@ func wellKnownServerURL(serverURL string) string { return serverURL + "/.well-known/librespeed" } +// refuseDowngrade is the redirect policy under --secure: a server asked over +// HTTPS may not send the client on to plain HTTP. The limit of ten redirects +// is the one Go applies when no policy is set. +func refuseDowngrade(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + if via[len(via)-1].URL.Scheme == "https" && req.URL.Scheme != "https" { + return errors.New("the server redirected to plain HTTP, which --secure does not allow") + } + return nil +} + // getServerList fetches the server JSON from a remote server func getServerList(forceScheme int, serverList string, excludes, specific []int, filter bool) ([]defs.Server, error) { // --exclude and --server cannot be used at the same time diff --git a/transfer_status_test.go b/transfer_status_test.go new file mode 100644 index 0000000..8e1a1eb --- /dev/null +++ b/transfer_status_test.go @@ -0,0 +1,101 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// transferBackend answers the probe and the IP lookup, and its download URL +// with the given status. +func transferBackend(t *testing.T, downloadStatus int) *httptest.Server { + t.Helper() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/empty.php": + case "/getIP.php": + w.Write([]byte(`{"processedString":"127.0.0.1 - localhost","rawIspInfo":""}`)) + case "/garbage.php": + w.WriteHeader(downloadStatus) + w.Write([]byte(strings.Repeat("x", 64<<10))) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv +} + +// A server that answers its probe but whose download URL does not exist gives +// nothing to measure. The run fails and names the status in every mode, not +// reporting the speed at which the error pages arrived. +func TestMissingDownloadURLFailsTheRun(t *testing.T) { + backend := transferBackend(t, http.StatusNotFound) + list := writeServerList(t, listedServer{1, "Up", backend.URL, "empty.php"}) + + for _, mode := range outputModes { + t.Run("mode="+mode, func(t *testing.T) { + r := runCLI(t, withMode(mode, "--local-json", list, "--server", "1", "--duration", "1", "--no-icmp", "--no-upload")...) + + if r.code != 1 { + t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr) + } + // the event stream has announced its phases by then + if strings.Contains(r.stdout, "Up") || strings.Contains(r.stdout, "rate") { + t.Errorf("stdout = %q, want no report", r.stdout) + } + if msg, want := r.failure(t), "Selected server Up (127.0.0.1) gave no result: the download request returned HTTP 404 Not Found"; msg != want { + t.Errorf("error = %q, want %q", msg, want) + } + if strings.Contains(r.stderr, "Download rate") { + t.Errorf("a rate is printed for the failed test:\n%s", r.stderr) + } + if n := strings.Count(r.stderr, "HTTP 404 Not Found"); n != 1 { + t.Errorf("the cause is on stderr %d times, want once:\n%s", n, r.stderr) + } + }) + } +} + +// With more than one server, one whose download fails does not take the +// results of the others with it. +func TestFailedDownloadLeavesTheRunToTheOtherServers(t *testing.T) { + good := transferBackend(t, http.StatusOK) + bad := transferBackend(t, http.StatusNotFound) + list := writeServerList(t, + listedServer{1, "Bad", bad.URL, "empty.php"}, + listedServer{2, "Good", good.URL, "empty.php"}, + ) + args := []string{"--local-json", list, "--server", "1", "--server", "2", "--duration", "1", "--no-icmp", "--no-upload"} + + r := runCLI(t, append(args, "--json")...) + + if r.code != 0 { + t.Errorf("exit status %d, want 0, stderr:\n%s", r.code, r.stderr) + } + var reports []struct { + Server struct { + Name string `json:"name"` + } `json:"server"` + Download float64 `json:"download"` + } + if err := json.Unmarshal([]byte(r.stdout), &reports); err != nil { + t.Fatalf("stdout is not a JSON report: %v\n%s", err, r.stdout) + } + if len(reports) != 1 || reports[0].Server.Name != "Good" || reports[0].Download <= 0 { + t.Errorf("reports = %+v, want the one of Good with a download rate", reports) + } + const cause = "Failed to get download speed: the download request returned HTTP 404 Not Found\n" + if !strings.Contains(r.stderr, cause) { + t.Errorf("stderr does not say why Bad failed:\n%s", r.stderr) + } + + // the failed server's output is set apart from the next one's like any other + r = runCLI(t, args...) + if !strings.Contains(r.stderr, cause+"\nSelected server: Good ") { + t.Errorf("no blank line between the failed server and the next:\n%s", r.stderr) + } +}