Skip to content

fix: transfers without data and plain HTTP redirects under --secure - #160

Open
BKPepe wants to merge 2 commits into
librespeed:masterfrom
BKPepe:fix/transfer-status-codes
Open

BKPepe wants to merge 2 commits into
librespeed:masterfrom
BKPepe:fix/transfer-status-codes

Conversation

@BKPepe

@BKPepe BKPepe commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Two commits, rebased onto #154. The second needs the first.

A download or upload URL that answers with an error status was timed as if the error pages were data. Such an answer no longer counts. An upload is not sent on after a redirect any more: a 301, 302 or 303 was followed as a GET without the payload and counted. A request that fails is followed by a new one after 200 ms, and a server with no accepted request fails like one that is down.

An upload with no accepted request is still reported where a request had been sending, as on a slow uplink or with --no-pre-allocate. A connection dropped at once does not count, nor a payload that was handed over within 250 ms and never answered. A stream cut with 413 counts, and one dropped connection no longer fails a --no-pre-allocate run.

Under --secure a server could redirect to http://, and the probe, the IP lookup, the transfers and the telemetry request followed. Such a redirect is now refused.

Upload against a local server, link shaped with netem:

20 Mbit, server answers 500:                                 master 20.6 Mbps, exit 0   now exit 1
20 Mbit, --no-pre-allocate --duration 10, one dropped POST:  master exit 1              now 21.9 Mbps
100 Mbit, server takes the payload and hangs:                master 2.7 Mbps, exit 0    now exit 1

A server that hangs is still reported at a low rate where the link is too slow to take the payload at once. With --insecure, a server that redirects its upload to HTTPS now fails the upload instead of reporting a rate that was no measurement.

@BKPepe
BKPepe force-pushed the fix/transfer-status-codes branch from c34f6d4 to 45a48a8 Compare November 22, 2026 14:34

@maddie maddie left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the head 45a48a8 against master. The redirect and refused-status work is solid; the headline "transfers without data" fix is complete for downloads but has a hole on the upload side. Both ❌ below are the same root cause: a request that fails at the transport level, or that is read but never answered, leaves neither lastErr nor succeeded set, so Upload falls through to a 0 Mbps "success".

❌ error — defs/server.go:608-614

The transport-error branch returns before lastErr.Store and before signalling uploadDone. The final check at defs/server.go:713 only fires when lastErr != nil, so a request that never reached a server is invisible.

Reproduced on this tree:

  • dead port (http://127.0.0.1:9): rate=0.000 total=0 err=<nil> (download at the same address correctly returns dial tcp 127.0.0.1:9: connect: connection refused)
  • listener that accepts and never answers: rate=0.109 total=16384 err=<nil>
  • handler that hijacks and closes every connection: rate=0.187 total=32768 err=<nil> after 12 attempts
  • CLI --no-download --upload-size 16 --json against a dead backend: exit 0 with "upload":0.25 and only bytes_sent

For a blackholed address the test window ends while the write is still in flight, so the branch is not even reached; nothing is recorded either way.

Fix: mirror doDownload. If ctx.Err() != nil, the window ended and returning is right. Otherwise store the error, pause, signal uploadDone so a replacement request is spawned, and return:

resp, err := http.DefaultClient.Do(uploadReq)
if err != nil && resp == 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.
    if !pauseBeforeRetry(ctx) {
        return
    }
    select {
    case uploadDone <- struct{}{}:
    case <-ctx.Done():
    }
    return
}

❌ error — defs/server.go:712-717

Unlike Download at defs/server.go:523-533, the final upload decision has no !succeeded branch. A server that reads the POST and never answers therefore reports success with the bytes it swallowed. Probe: rate=0.1869 total=32768 err=<nil> from a handler that reads the body and blocks; http.Client hits its timeout only after the test window is over, so no error is ever stored.

Fix, keeping the --no-pre-allocate timeout case working (that upload is still sending when the window ends, and its bytes are real; my first attempt without the isTimeout exemption broke it into context deadline exceeded (Client.Timeout exceeded while awaiting headers) with 1.04 GB sent):

// no accepted request is not a result. 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; anything else with nothing accepted is a
// broken path, even when the test window ended before it failed.
if !succeeded.Load() {
    failed = true
    err := lastErr.Load()
    if err != nil && !isTimeout(*err) {
        return 0, 0, *err
    }
    if err == nil || counter.Total() == 0 {
        return 0, 0, errors.New("no upload request was answered before the test ended")
    }
}
return counter.AvgMbps(), counter.Total(), nil

with

// isTimeout reports whether err is a network timeout, such as the client
// timeout of a --no-pre-allocate upload whose body never ends.
func isTimeout(err error) bool {
    var netErr net.Error
    return errors.As(err, &netErr) && netErr.Timeout()
}

I validated exactly this patch on top of 45a48a8 (one file, defs/server.go, +33/−5): the four probes above now fail with connection refused / no upload request was answered before the test ended / read: connection reset by peer, the all-500 case is unchanged, --no-pre-allocate still reports rate=4507 total=1070628864 err=<nil> (server saw 1070399488), and go build, go vet, go test -count=1 ./... and go test -count=1 -race ./... all pass. Happy to push it to fix/transfer-status-codes if you'd rather not write it yourself — say the word.

💡 nit — speedtest/speedtest.go:321

http.DefaultClient.CheckRedirect is process-global and never restored. The CLI exits right after, so users are unaffected, but speedtest.SpeedTest is exported: a later in-process call, or any unrelated request on http.DefaultClient, keeps the --secure downgrade policy. Save and restore it with defer, or use a dedicated *http.Client for the test requests.

💡 nit — defs/server.go:523-533

A working but slow server whose first download byte arrives after --duration is now a hard exit 1 with "no download request was answered before the test ended" (probe with 1.5 s time-to-first-byte and a 1 s duration). That may well be the intent, but it is a new user-visible behaviour; worth a test or a line in the PR description.

💡 nit — test coverage

There is no regression test for either ❌ (upload transport error, upload read-but-never-answered). Adding the three cheap ones — dead port via 127.0.0.1:9, a raw listener that reads and never answers, and a handler that hijacks and closes — would pin the behaviour without needing long windows. separate/noneResponding in speedtest/helper.go:315 are only covered indirectly through the CLI tests.

Verified as correct

  • refuseDowngrade (speedtest/speedtest.go:437) rejects https→http while allowing http→http under --insecure; the 10-redirect cap from net/http still applies; relative and scheme-relative targets resolve before the check.
  • fetch/refusal treat any 2xx as accepted and name the status otherwise; download and upload both report the upload request returned HTTP 500 Internal Server Error when every request is refused.
  • pauseBeforeRetry respects ctx and does not spin on a refused connection.
  • separate/noneResponding texts are correct for one and many dead servers.
  • On master (096d72a) with the new tests copied over, the download path still fabricates 2081 Mbps from 404 pages and the defs assertions fail, so the tests do guard the fix.

@maddie maddie left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the new head 84ca61c against master. The transport-error half of the previous review is fixed: a dead port and an immediate hijack/close now end with an error, and the new refusal/redirect work is sound. One critical case from the previous review is still present.

❌ error — defs/server.go:625 and defs/server.go:763-775

A server that reads the whole POST and then never answers is still reported as a successful upload.

sent.since() at defs/server.go:811-818 measures the time since the first byte, not the time spent sending. A normal pre-allocated body is written in one burst, so since() grows past sendingProof (250 ms) while the client is merely waiting for a response. sending therefore becomes true, carried is set, and the final !succeeded gate falls through to counter.AvgMbps().

Probe on this head:

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    io.Copy(io.Discard, r.Body)
    <-r.Context().Done()
}))
s := &Server{Server: ts.URL, UploadURL: "empty.php"}
mbps, total, err := s.Upload(false, true, false, false, 1, 16, time.Second)
// mbps=0.10911747108565795 total=16384 err=<nil>

That is the same 0.109 Mbps / 16384 bytes / nil result as the previous review, and it is not a measurement of the uplink: the server took the payload and stopped. The sendingProof guard was intended to reject a connection dropped at once, but a fully written 16 KiB body always passes it.

Fix: only treat a request as “still sending” when its body is actually incomplete. For a pre-allocated upload, compare what was written with the payload length; --no-pre-allocate is still sending by definition. This also preserves the slow-uplink and no-pre-allocate cases the tests pin.

payloadLen := 0
if noPrealloc {
    bodyReader = &SeekWrapper{rand.Reader}
} else {
    payloadLen = len(counter.Payload())
    bodyReader = bytes.NewReader(counter.Payload())
}
// ...
stillSending := noPrealloc || !sent.wroteAll(payloadLen)
sending := resp == nil && stillSending && sent.since() >= sendingProof
// ...
func (s *sentBytes) wroteAll(limit int) bool {
    s.mu.Lock()
    defer s.mu.Unlock()
    return limit > 0 && s.n >= uint64(limit)
}

I validated this on top of 84ca61c (one file, defs/server.go, +17/−1): the probe above becomes 0 0 no upload request was answered before the test ended; TestUploadCountsWhatASlowUplinkSent, TestUploadCountsAStreamThatNeverEnds, TestUploadFailsWhenEveryRequestIsDropped, TestUploadFailsWhenNothingIsSent and the rest of go test -count=1 ./... pass, as do go build ./..., go vet ./... and gofmt -l .. Please add a regression test for the read-then-hang case; the current upload tests only cover an immediate drop and a never-sending transport.

💡 nit — defs/server.go:625

After the body-completeness fix, since() is still the time since the first byte. A request that sends a few bytes and then stalls for the rest of the window will still look like a slow uplink. Tracking the last successful write (or requiring recent write progress) would tighten that case too, though it is less clear-cut than the fully-read body above.

💡 nit — test coverage

TestUploadFailsWhenEveryRequestIsDropped now depends on the hijack happening within 250 ms of the first write. On a heavily loaded CI machine, the same test could flip to carried and fail. The body-completeness check above makes the test independent of that timing, which is another reason to add it.

I’m happy to push the patch to fix/transfer-status-codes if you prefer not to write it yourself.

@BKPepe
BKPepe force-pushed the fix/transfer-status-codes branch from 84ca61c to 1fd0c2d Compare November 24, 2026 12:13

@maddie maddie left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the rework. The no-data and error-status handling is much better, and the full test suite and CI are green on 1fd0c2d. I found two remaining correctness problems in the upload result path; both produce a successful-looking result when there was no upload measurement.

❌ error: a fully handed-over payload that is never answered still succeeds after 250 ms

defs/server.go:847-853 makes sentBytes.sending return true for a payload that was handed over whole, as long as the handover took at least sendingProof (250 ms). The final gate at defs/server.go:788-801 then returns the counted bytes as a result when carried is set.

That is the read-then-hang case from the previous review, just slower than the new 16 KiB regression test. With the default 1 MiB payload on a 20 Mbps link, the server reads the entire body and never answers:

default 1 MiB: err=<nil> total=1048576 serverRead=1048576 writes=33 bytes=1048717 handover=587.892812ms

The probe was a local httptest server that did io.Copy(io.Discard, r.Body) and then waited for r.Context().Done(). The upload returned success with 1 MiB counted, although the server never answered. defs/transfer_status_test.go:442-445 says a payload taken and not answered is a failure; the current heuristic only enforces that when the handover finishes within 250 ms. The comment at defs/server.go:784-787 acknowledges the gap.

The distinction should be whether the request is still sending, not how long the handover took. Suggest making sending return false once whole is set, for example only count a preallocated request while s.whole.IsZero() (the body is still in flight), keeping the existing lasted/250 ms guard for bytes that actually crossed the link. That preserves TestUploadCountsWhatASlowUplinkSent (the 32 MiB body is still being sent when the test ends) while failing the default 1 MiB read-then-hang case. Please add a regression test with a 1 MiB payload throttled to roughly 4 KiB / 1.6 ms, so the handover takes about 400 ms.

❌ error: a 302 redirect of the upload POST is followed as GET and counted as a successful upload

defs/server.go:662-667 sets succeeded whenever refusal("upload", resp) returns nil. Go's default redirect policy follows 301/302/303 as a GET and drops the POST body, so a server that answers 302 to /empty.php and redirects to a page that returns 200 is accepted as a successful upload.

A local probe with a front server returning 302 to a backend that returns 200 to the redirected GET produced:

mbps=359.9417332996685 total=31522816 err=<nil> front=1924 backend=1924

Every one of the 1924 requests was a POST with a 16 KiB body; the backend received a GET with a zero-length body. The total is exactly 1924 × 16384. This also happens on master, but this PR rewrites the result path and its stated goal is that a server with no accepted request must not report a result; the new gate still accepts this case. The 307 probe correctly fails with the upload request returned HTTP 307 Temporary Redirect, so only the method-changing redirects are missed.

Please reject the response when the final request is not a POST, for example:

if resp.Request.Method != http.MethodPost {
    err = fmt.Errorf("the upload request was redirected to a %s request", resp.Request.Method)
} else {
    err = refusal("upload", resp)
}

or install an upload-specific CheckRedirect that refuses 301/302/303. Add a test with a 302 to a 200 GET endpoint, asserting an error and zero counted bytes.

💡 nit: --secure policy starts after the server list is fetched

speedtest/speedtest.go:335-379 installs refuseDowngrade only after getServerList returns. An HTTPS server-list URL can therefore still be redirected to plain HTTP. If that exception is intentional, please document it; otherwise install the policy before the first getServerList call and cover it with a test. This is not a blocker for the two correctness fixes above.

Once these are addressed I can re-review and merge. The PR is otherwise well covered, and the 307/308, refused-request, and multi-server fallthrough behavior looks solid.

@maddie

maddie commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

One more ❌ error I found while checking the 413 path, in addition to the two in the review above.

❌ error: a fast 413 on --no-pre-allocate is treated as a refusal and loses the bytes that crossed

defs/server.go:650 still requires the 250 ms sendingProof for the tooLarge branch:

streamed := sent.sending(timedOut) && (resp == nil || tooLarge)

A server that reads part of the never-ending --no-pre-allocate stream and answers 413 Request Entity Too Large immediately therefore takes the refusal path instead of the accepted "server cut the stream" path. Probe result:

mbps=0 total=0 err=the upload request returned HTTP 413 Request Entity Too Large read=4194304

The server read 4 MiB from the stream; the client reported zero bytes and an error. defs/transfer_status_test.go:529+ only covers a 413 after a 500 ms read, so it passes while this fast case fails. The 413 status itself proves the server consumed the stream, so the time-based proof is not needed there.

Suggested fix: add sentBytes.started() returning !first.IsZero() under the existing mutex, then use:

streamed := (tooLarge && sent.started()) || (resp == nil && sent.sending(timedOut))

Keep pre-allocated 413s as refusals; tooLarge already requires noPrealloc.

💡 test-quality nits

  • defs/transfer_status_test.go:446-470 uses 16 KiB over loopback for the read-then-hang case. It passes only while the whole body is handed over in under 250 ms; under CI load it can start reporting success, which is the bug direction. The deterministic 1 MiB throttled case from the review above should be the regression test.
  • secure_redirect_test.go:36-59 checks only the refusal error; unlike the download/upload/telemetry tests, it does not count requests reaching the plain backend. Add an atomic counter and assert it stays zero, so a request sent before the refusal cannot pass.

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.
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.
@BKPepe
BKPepe force-pushed the fix/transfer-status-codes branch from 1fd0c2d to 168a242 Compare November 25, 2026 09:58
@BKPepe

BKPepe commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Thanks, all three reproduce. Before taking the rule that a request whose payload is handed over whole is no longer sending, I measured it on a link shaped with netem, upload only:

link                               master         1fd0c2d        your rule
1 Mbit, queue 1000                 1.53 Mbps      1.53 Mbps      0.45 Mbps
500 kbit, --concurrent 1           0.55 Mbps      0.55 Mbps      exit 1
20 Mbit, server reads and hangs    2.22, exit 0   2.49, exit 0   0.66, exit 0

On a slow uplink the whole payload sits in the buffers on the way long before the server has it, and the client cannot tell that from a server that took it and hangs. Keeping the bytes of the timed-out requests fixes the first row but not the second. So the 250 ms rule stays, your 1 MiB case is still reported, and the 16 KiB cases still depend on the 250 ms. A request that times out keeps its bytes now. Telling the two apart would take the socket's send queue, which I have not tried.

Uploads do not follow redirects any more, so a 301, 302 or 303 is refused like a 307 and no GET goes to the target. With --insecure that fails the public servers that redirect uploads to HTTPS, until the redirect follow-up goes in. The fast 413 counts with started(), the redirect test counts the plain requests, and the server list stays outside --secure on purpose, as its help text says.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants