From 2713b943d7dc4db7d021b458dc065d66fb416396 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Sat, 21 Nov 2026 23:44:39 +0100 Subject: [PATCH 1/3] fix: do not report a transfer that got no data as a result A download or upload URL that answered with an error status, or an upload URL that answered with a redirect, was timed as if it carried data. Such answers are not counted now, and a server that only refuses fails like one that is down. --- defs/bytes_counter.go | 5 + defs/server.go | 333 +++++++++++--- defs/transfer_status_test.go | 829 +++++++++++++++++++++++++++++++++++ speedtest/helper.go | 70 ++- transfer_status_test.go | 101 +++++ 5 files changed, 1250 insertions(+), 88 deletions(-) create mode 100644 defs/transfer_status_test.go create mode 100644 transfer_status_test.go 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/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/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) + } +} From 168a24292bb497085a1c88e0a094b3781fb92750 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Sun, 22 Nov 2026 01:21:30 +0100 Subject: [PATCH 2/3] fix: refuse a redirect from HTTPS to plain HTTP under --secure A server could answer with a redirect to an http:// URL, and the probe, the IP lookup, the transfers and the telemetry request followed it. A run that asked for HTTPS was then measured, or its result sent, over plain HTTP. --- secure_redirect_test.go | 186 +++++++++++++++++++++++++++++++++++++ speedtest/redirect_test.go | 47 ++++++++++ speedtest/speedtest.go | 29 ++++++ 3 files changed, 262 insertions(+) create mode 100644 secure_redirect_test.go create mode 100644 speedtest/redirect_test.go 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/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 From 8487a4b6f3b51ad23e10f75efaa664913024a803 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Sun, 22 Nov 2026 10:21:16 +0100 Subject: [PATCH 3/3] fix: send the upload to where its URL redirects An upload does not follow a redirect, so a server whose upload URL redirects, as most public servers do under --insecure, gave no upload result. A server whose probe is redirected is now asked with an empty POST where its upload URL is. The test runs there if it is on the same server, where plain HTTP may become HTTPS. --- defs/server.go | 144 ++++++++++++++- defs/upload_redirect_test.go | 331 +++++++++++++++++++++++++++++++++++ secure_redirect_test.go | 102 ++++++++++- 3 files changed, 567 insertions(+), 10 deletions(-) create mode 100644 defs/upload_redirect_test.go diff --git a/defs/server.go b/defs/server.go index 81f97ce..eb2e4ac 100644 --- a/defs/server.go +++ b/defs/server.go @@ -47,6 +47,13 @@ type Server struct { // before every measurement. NegotiatedTLS *TLSInfo `json:"-"` Protocol string `json:"-"` // e.g. HTTP/3.0, filled by IsUp too + + // Whether the probe of this server was redirected. Filled by CheckUp, + // like NegotiatedTLS. Only such a server is asked where its upload URL + // is, see Upload. A server that redirects the POST of its upload and not + // the GET of the probe is not asked, so its upload gets the redirect as + // its answer and fails. + probeRedirected bool } // TLSInfo names the negotiated TLS parameters of a connection. @@ -65,13 +72,17 @@ func (s *Server) IsUp() bool { // CheckUp checks the speed test backend is up by accessing the ping URL, // which must answer 200 with an empty body, and returns why it is not up. -// Like IsUp, it records the negotiated TLS in s.NegotiatedTLS. +// Like IsUp, it records the negotiated TLS in s.NegotiatedTLS, and whether +// the probe was redirected. func (s *Server) CheckUp() error { t := time.Now() defer func() { s.TLog.Logf("Check backend is up took %s", time.Since(t).String()) }() + // not known until this probe is answered + s.probeRedirected = false + u, err := s.GetURL() if err != nil { return err @@ -93,6 +104,8 @@ func (s *Server) CheckUp() error { defer resp.Body.Close() s.Protocol = resp.Proto + // the last request has a redirect behind it if the client followed one + s.probeRedirected = resp.Request != nil && resp.Request.Response != nil // Report what the connection actually negotiated. On hardware without AES // acceleration the cipher, not the link, is what bounds the result, and @@ -591,6 +604,16 @@ func (s *Server) Upload(noPrealloc, silent, useBytes, useMebi bool, requests int defer cancel() u.Path = path.Join(u.Path, s.UploadURL) + // The payload has to go where the upload URL is, and a redirect moves + // it. A server whose probe was redirected is asked for that place. One + // whose probe was not gets no request it did not get before. + if s.probeRedirected { + if u, err = uploadTarget(ctx, u); err != nil { + output.WriteDebug("Failed to follow the upload URL: %s\n", output.Sanitize(err.Error())) + return 0, 0, err + } + } + // each finished request hands its worker back for a replacement uploadDone := make(chan int, requests) @@ -885,6 +908,125 @@ func (s *sentBytes) discount() { // HTTP/2 client, so the server is never left waiting for window. const downloadReadSize = 256 << 10 +// uploadProbeTimeout is how long uploadTarget may take in all. +var uploadProbeTimeout = 5 * time.Second + +// uploadTarget finds where the upload URL is, by sending it a POST without a +// body and going where the answers point. The HTTP client does not do that +// with the payload: it follows a POST answered with 301 or 302 as a GET, and +// it cannot send the body again on 307 or 308. The payload would go to a +// server that only redirects, and nothing behind it would be measured. +// +// A 303 is left alone. It answers a POST the server has taken and names a +// page to read, not another place to send the data to. +// +// Upload does not call this for a server whose probe was answered without +// a redirect. One that redirects a POST and not the GET of the probe is +// therefore tested as before. +// +// The payload stays with the listed server. A redirect may lead to another +// path there, and from plain HTTP to HTTPS, which is what the public servers +// that redirect their upload do. A redirect to another host or port is an +// error, and so is one that the client's policy refuses. Nothing is sent to +// the place such a redirect names. +// +// Unless the redirects end at a place that takes the empty POST, the test +// runs against the listed URL as it did before. That POST shows only that +// the place answers. Whether it reads the payload is not known, just as it +// is not known for the listed URL. +func uploadTarget(ctx context.Context, listed *url.URL) (*url.URL, error) { + client := *http.DefaultClient + policy := client.CheckRedirect + if policy == nil { + // what the client does on its own + policy = func(_ *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + return nil + } + } + // the answers are needed as they are, not as the client follows them + client.CheckRedirect = func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + } + + ctx, cancel := context.WithTimeout(ctx, uploadProbeTimeout) + defer cancel() + + target := listed + var via []*http.Request + var redirect *http.Response + for { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, target.String(), nil) + if err != nil { + return listed, nil + } + req.Header.Set("User-Agent", UserAgent) + if redirect != nil { + // the policy gets the request the way the client hands it over + req.Response = redirect + if err := policy(req, via); err != nil { + return nil, &url.Error{Op: "Post", URL: withoutQuery(target), Err: err} + } + if !sameServer(listed, target) { + return nil, &url.Error{Op: "Post", URL: withoutQuery(target), Err: errors.New("the upload URL redirects to another server")} + } + } + + resp, err := client.Do(req) + if err != nil { + output.WriteDebug("Could not ask where the upload URL is: %s\n", output.Sanitize(err.Error())) + return listed, nil + } + // a short page is read, so that the next hop can use the connection + io.Copy(io.Discard, io.LimitReader(resp.Body, 2<<10)) + resp.Body.Close() + + switch resp.StatusCode { + case http.StatusMovedPermanently, http.StatusFound, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: + location := resp.Header.Get("Location") + next, err := target.Parse(location) + if location == "" || err != nil { + output.WriteDebug("The upload URL redirects without a usable Location\n") + return listed, nil + } + output.WriteDebug("The upload URL redirects to %s\n", output.Sanitize(withoutQuery(next))) + via = append(via, req) + redirect = resp + target = next + continue + } + + if resp.StatusCode < 200 || resp.StatusCode > 299 { + if redirect != nil { + output.WriteDebug("The upload URL redirects to a place that answers HTTP %d, using the listed one\n", resp.StatusCode) + } + return listed, nil + } + return target, nil + } +} + +// sameServer reports whether next is at the server of the listed URL: its +// host and port are written as the listed URL writes them, and its scheme +// is the same or HTTPS in place of plain HTTP. The transport knows a test +// server by that host and port, so the upload goes over --http-version and +// is seen in the protocol report. +func sameServer(listed, next *url.URL) bool { + return listed.Host == next.Host && + (listed.Scheme == next.Scheme || listed.Scheme == "http" && next.Scheme == "https") +} + +// withoutQuery is u as a message shows it: without a password, a query or a +// fragment, any of which can carry a token. +func withoutQuery(u *url.URL) string { + shown := *u + shown.RawQuery, shown.ForceQuery = "", false + shown.Fragment, shown.RawFragment = "", "" + return shown.Redacted() +} + // 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 diff --git a/defs/upload_redirect_test.go b/defs/upload_redirect_test.go new file mode 100644 index 0000000..22f579a --- /dev/null +++ b/defs/upload_redirect_test.go @@ -0,0 +1,331 @@ +package defs + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" +) + +// uploadSeen is what a test server has seen of uploads: the bytes of payload +// it has read in POSTs, the POSTs that announced no body, and every request. +// A payload request that the end of the test cut short announces a body, even +// if none of it arrives. +type uploadSeen struct { + payload atomic.Int64 + emptyPOSTs atomic.Int64 + requests atomic.Int64 +} + +func (u *uploadSeen) count(r *http.Request) { + u.requests.Add(1) + if r.Method != http.MethodPost { + return + } + if r.ContentLength == 0 { + u.emptyPOSTs.Add(1) + } + n, _ := io.Copy(io.Discard, r.Body) + u.payload.Add(n) +} + +// movedServer is a server whose every URL answers with the given redirect to +// the same path under /moved, and what the two places have seen. +func movedServer(t *testing.T, status int) (s *Server, listed, target *uploadSeen) { + t.Helper() + listed, target = new(uploadSeen), new(uploadSeen) + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/moved/") { + target.count(r) + return + } + listed.count(r) + http.Redirect(w, r, "/moved"+r.URL.Path, status) + })) + t.Cleanup(ts.Close) + + return &Server{Server: ts.URL, PingURL: "empty.php", UploadURL: "empty.php"}, listed, target +} + +// A server that has moved gets the payload at its new place. Its probe is +// redirected, so the upload asks once, with an empty POST, where its URL is. +// Sent to the listed URL, the payload only reaches a server that redirects, +// and the HTTP client then asks the new place with a GET, or not at all. +func TestUploadFollowsItsURL(t *testing.T) { + const ( + requests = 2 + uploadSizeKiB = 16 + ) + + for _, status := range []int{ + http.StatusMovedPermanently, + http.StatusFound, + http.StatusTemporaryRedirect, + http.StatusPermanentRedirect, + } { + t.Run(strconv.Itoa(status), func(t *testing.T) { + s, listed, target := movedServer(t, status) + if err := s.CheckUp(); err != nil { + t.Fatalf("CheckUp returned error: %v", err) + } + + _, total, err := s.Upload(false, true, false, false, requests, uploadSizeKiB, 500*time.Millisecond) + + if err != nil { + t.Fatalf("Upload returned error: %v", err) + } + if n := listed.payload.Load(); n != 0 { + t.Errorf("%d bytes of payload went to the URL that redirects, want none", n) + } + if a, b := listed.emptyPOSTs.Load(), target.emptyPOSTs.Load(); a != 1 || b != 1 { + t.Errorf("%d empty POSTs at the listed URL and %d at the new place, want one each", a, b) + } + // what is counted is what the new place has read from POSTs, but + // for the requests that the end of the test cut short + read := target.payload.Load() + unread := int64(total) - read + if read == 0 || unread < 0 || unread > requests*uploadSizeKiB*1024 { + t.Errorf("%d bytes counted and %d read from POSTs at the new place", total, read) + } + }) + } +} + +// A server whose probe is not redirected is asked nothing before the upload. +// It gets the requests it always got. +func TestUploadAsksNothingOfAServerThatDoesNotRedirect(t *testing.T) { + var seen uploadSeen + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen.count(r) + })) + t.Cleanup(ts.Close) + s := &Server{Server: ts.URL, PingURL: "empty.php", UploadURL: "empty.php"} + if err := s.CheckUp(); err != nil { + t.Fatalf("CheckUp returned error: %v", err) + } + + _, total, err := s.Upload(false, true, false, false, 2, 16, 500*time.Millisecond) + + if err != nil { + t.Fatalf("Upload returned error: %v", err) + } + if total == 0 { + t.Error("nothing was uploaded") + } + if n := seen.emptyPOSTs.Load(); n != 0 { + t.Errorf("the server got %d POSTs without a body, want none", n) + } +} + +// Unless the redirects end at a place that takes the empty POST, the server +// is tested the way it was before, against the listed URL. These servers +// count as ones whose probe was redirected, so they are asked. +func TestUploadDoesNotDependOnTheEmptyPOST(t *testing.T) { + timeout := uploadProbeTimeout + uploadProbeTimeout = 100 * time.Millisecond + t.Cleanup(func() { uploadProbeTimeout = timeout }) + + for _, tc := range []struct { + name string + answer http.HandlerFunc + }{ + {"an error status", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) }}, + {"no answer", func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }}, + {"a redirect to nowhere", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusFound) }}, + {"a redirect to a place that takes no POST", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/elsewhere", http.StatusFound) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path != "/empty.php": + w.WriteHeader(http.StatusMethodNotAllowed) + case r.ContentLength == 0: + tc.answer(w, r) + default: + io.Copy(io.Discard, r.Body) + } + })) + t.Cleanup(ts.Close) + s := &Server{Server: ts.URL, UploadURL: "empty.php", probeRedirected: true} + + _, total, err := s.Upload(false, true, false, false, 2, 16, 500*time.Millisecond) + + if err != nil { + t.Fatalf("Upload returned error: %v", err) + } + if total == 0 { + t.Error("nothing was uploaded") + } + }) + } +} + +// Redirects that lead nowhere end where the HTTP client ends them itself, +// and before any payload is sent. +func TestUploadStopsFollowingALoop(t *testing.T) { + var asked, payload atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + n, _ := io.Copy(io.Discard, r.Body) + payload.Add(n) + http.Redirect(w, r, r.URL.Path, http.StatusTemporaryRedirect) + })) + t.Cleanup(ts.Close) + s := &Server{Server: ts.URL, UploadURL: "empty.php", probeRedirected: true} + + _, _, err := s.Upload(false, true, false, false, 2, 16, 500*time.Millisecond) + + if err == nil || !strings.HasSuffix(err.Error(), "stopped after 10 redirects") { + t.Errorf("error = %v, want the limit of 10 redirects named", err) + } + if n := asked.Load(); n != 10 { + t.Errorf("the URL was asked %d times, want 10", n) + } + if n := payload.Load(); n != 0 { + t.Errorf("%d bytes of payload were sent into the loop, want none", n) + } +} + +// The upload stays with the listed server. A redirect to another port or +// another host name ends the test before anything is sent there, not even +// the empty POST. +func TestUploadStaysWithTheListedServer(t *testing.T) { + const refused = "the upload URL redirects to another server" + + for _, status := range []int{http.StatusMovedPermanently, http.StatusTemporaryRedirect} { + for _, place := range []string{"another port", "another host"} { + t.Run(place+" "+strconv.Itoa(status), func(t *testing.T) { + var listed, elsewhere uploadSeen + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + elsewhere.count(r) + })) + t.Cleanup(other.Close) + + var ts *httptest.Server + ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.Host, "localhost:") { + elsewhere.count(r) + return + } + listed.count(r) + there := other.URL + if place == "another host" { + there = strings.Replace(ts.URL, "127.0.0.1", "localhost", 1) + } + http.Redirect(w, r, there+"/moved"+r.URL.Path, status) + })) + t.Cleanup(ts.Close) + s := &Server{Server: ts.URL, UploadURL: "empty.php", probeRedirected: true} + + _, total, err := s.Upload(false, true, false, false, 2, 16, 500*time.Millisecond) + + if err == nil || !strings.HasSuffix(err.Error(), refused) { + t.Errorf("error = %v, want it to end in %q", err, refused) + } + if total != 0 { + t.Errorf("%d bytes counted, want none", total) + } + if n := elsewhere.requests.Load(); n != 0 { + t.Errorf("%d requests went to the other server, want none", n) + } + if a, b := listed.emptyPOSTs.Load(), listed.payload.Load(); a != 1 || b != 0 { + t.Errorf("%d empty POSTs and %d bytes of payload at the listed URL, want one and none", a, b) + } + }) + } + } +} + +// The empty POST shows only that a place answers. One that answers without +// reading gets the payload all the same, as a listed URL that does so does. +func TestUploadGoesWhereTheEmptyPOSTIsAnswered(t *testing.T) { + var listedPayloads, payloads atomic.Int64 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/moved/empty.php" { + if r.ContentLength > 0 { + listedPayloads.Add(1) + } + http.Redirect(w, r, "/moved/empty.php", http.StatusTemporaryRedirect) + return + } + // answered without a read of the body + if r.ContentLength > 0 { + payloads.Add(1) + } + })) + t.Cleanup(ts.Close) + s := &Server{Server: ts.URL, UploadURL: "empty.php", probeRedirected: true} + + _, _, err := s.Upload(false, true, false, false, 2, 16, 500*time.Millisecond) + + if err != nil { + t.Fatalf("Upload returned error: %v", err) + } + if n := payloads.Load(); n == 0 { + t.Error("no payload went to the place that answered the empty POST") + } + if n := listedPayloads.Load(); n != 0 { + t.Errorf("%d payloads went to the listed URL, want none", n) + } +} + +func TestSameServer(t *testing.T) { + for _, tc := range []struct { + listed, next string + want bool + }{ + {"http://h/empty.php", "/moved/empty.php", true}, + {"http://h:8080/empty.php", "http://h:8080/moved/empty.php", true}, + {"https://h:8443/empty.php", "https://h:8443/moved/empty.php", true}, + {"http://h/empty.php", "https://h/empty.php", true}, + {"http://h:8080/empty.php", "https://h:8080/empty.php", true}, + {"http://[::1]/empty.php", "https://[::1]/empty.php", true}, + {"https://h/empty.php", "http://h/empty.php", false}, + {"http://h/empty.php", "http://h:8080/empty.php", false}, + {"http://h:8080/empty.php", "https://h:8443/empty.php", false}, + {"http://h/empty.php", "https://h:8443/empty.php", false}, + {"http://h/empty.php", "http://www.h/empty.php", false}, + {"http://h/empty.php", "http://other/empty.php", false}, + {"http://h/empty.php", "//other/empty.php", false}, + {"http://127.0.0.1/empty.php", "http://localhost/empty.php", false}, + // the same server written another way, which the transport would + // not know as the test server + {"http://h:80/empty.php", "https://h/empty.php", false}, + {"http://h/empty.php", "https://h:443/empty.php", false}, + {"http://H/empty.php", "http://h/empty.php", false}, + } { + listed, err := url.Parse(tc.listed) + if err != nil { + t.Fatal(err) + } + next, err := listed.Parse(tc.next) + if err != nil { + t.Fatal(err) + } + if got := sameServer(listed, next); got != tc.want { + t.Errorf("sameServer(%s, %s) = %v, want %v", tc.listed, tc.next, got, tc.want) + } + } +} + +// A redirect URL is shown without what can carry a token. +func TestWithoutQuery(t *testing.T) { + u, err := url.Parse("https://user:secret@h/empty.php?token=abc#frag") + if err != nil { + t.Fatal(err) + } + if got, want := withoutQuery(u), "https://user:xxxxx@h/empty.php"; got != want { + t.Errorf("withoutQuery = %q, want %q", got, want) + } + if u.RawQuery == "" || u.Fragment == "" { + t.Error("withoutQuery changed the URL it was given") + } +} diff --git a/secure_redirect_test.go b/secure_redirect_test.go index c40bb96..063de8b 100644 --- a/secure_redirect_test.go +++ b/secure_redirect_test.go @@ -3,7 +3,6 @@ package main import ( "net/http" "net/http/httptest" - "strconv" "strings" "sync/atomic" "testing" @@ -89,28 +88,42 @@ func TestSecureRefusesARedirectedDownload(t *testing.T) { } } -// 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. +// And when only the upload is redirected. A server whose probe was not +// redirected is not asked where its upload URL is, so the redirect meets the +// payload, which does not follow it and gets it as a status. A server that +// redirected its probe, here to another HTTPS URL, is asked first, and the +// redirect is refused there. Nothing goes on over plain HTTP in any of these. func TestSecureRefusesARedirectedUpload(t *testing.T) { for _, tc := range []struct { - status int - want string + name string + status int + probeRedirected bool + want string }{ - {http.StatusFound, "the upload request returned HTTP 302 Found"}, - {http.StatusTemporaryRedirect, "the upload request returned HTTP 307 Temporary Redirect"}, + {"302", http.StatusFound, false, "the upload request returned HTTP 302 Found"}, + {"307", http.StatusTemporaryRedirect, false, "the upload request returned HTTP 307 Temporary Redirect"}, + {"302 after a redirected probe", http.StatusFound, true, refusedRedirect}, + {"307 after a redirected probe", http.StatusTemporaryRedirect, true, refusedRedirect}, } { - t.Run(strconv.Itoa(tc.status), func(t *testing.T) { + t.Run(tc.name, 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) + var questions, payloads atomic.Int64 front := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodPost: + if r.ContentLength == 0 { + questions.Add(1) + } else { + payloads.Add(1) + } http.Redirect(w, r, backend.URL+r.URL.RequestURI(), tc.status) + case r.URL.Path == "/empty.php" && tc.probeRedirected: + http.Redirect(w, r, "/moved.php", http.StatusMovedPermanently) case r.URL.Path == "/getIP.php": w.Write([]byte(`{"processedString":"127.0.0.1 - localhost","rawIspInfo":""}`)) } @@ -135,6 +148,77 @@ func TestSecureRefusesARedirectedUpload(t *testing.T) { if n := overPlainHTTP.Load(); n != 0 { t.Errorf("%d requests went on over plain HTTP, want none", n) } + // where the redirect was met: at the empty POST that asks, or at + // the payload + asked, sent := questions.Load(), payloads.Load() + if tc.probeRedirected && (asked != 1 || sent != 0) { + t.Errorf("%d empty POSTs and %d with a payload, want one and none", asked, sent) + } + if !tc.probeRedirected && (asked != 0 || sent == 0) { + t.Errorf("%d empty POSTs and %d with a payload, want none and some", asked, sent) + } + }) + } +} + +// An upload that an HTTPS server redirects to another HTTPS server stays +// where it is, with --secure or without it. Not a request of any kind goes to +// the other server. +func TestARedirectedUploadStaysWithItsServer(t *testing.T) { + for _, secure := range []bool{false, true} { + name := "without --secure" + if secure { + name = "with --secure" + } + t.Run(name, func(t *testing.T) { + var elsewhere atomic.Int64 + other := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + elsewhere.Add(1) + })) + t.Cleanup(other.Close) + + var questions, payloads atomic.Int64 + front := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost: + if r.ContentLength == 0 { + questions.Add(1) + } else { + payloads.Add(1) + } + http.Redirect(w, r, other.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) + case r.URL.Path == "/empty.php": + http.Redirect(w, r, "/moved.php", http.StatusMovedPermanently) + 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"}) + args := []string{"--local-json", list, "--server", "1", "--skip-cert-verify", + "--duration", "1", "--no-icmp", "--no-download", "--upload-size", "16", "--json"} + if secure { + args = append(args, "--secure") + } + r := runCLI(t, args...) + + 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) + } + const refused = "the upload URL redirects to another server" + if msg := r.failure(t); !strings.HasSuffix(msg, refused) { + t.Errorf("error = %q, want it to end in %q", msg, refused) + } + if n := elsewhere.Load(); n != 0 { + t.Errorf("%d requests went to the other server, want none", n) + } + if asked, sent := questions.Load(), payloads.Load(); asked != 1 || sent != 0 { + t.Errorf("%d empty POSTs and %d with a payload, want one and none", asked, sent) + } }) } }