From 3643afbce3529799aa18f44b2548f4155fe39358 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Mon, 23 Nov 2026 13:39:31 +0100 Subject: [PATCH 1/4] test: cover what the option and pinger fixes left untested The largest upload size, the short forms of contradicting options, the source address and mark of a bound connection, and a family localhost has no address in were not asserted. The comment on newPinger now says what an unknown network does. --- contradictory_options_test.go | 7 +++ defs/pinger_test.go | 9 ++-- defs/server.go | 7 +-- options_test.go | 48 ++++++++++++++++++ speedtest/dialer_linux_test.go | 93 +++++++++++++++++++++++++++++++++- 5 files changed, 156 insertions(+), 8 deletions(-) diff --git a/contradictory_options_test.go b/contradictory_options_test.go index 0f56b2c..43242f4 100644 --- a/contradictory_options_test.go +++ b/contradictory_options_test.go @@ -21,6 +21,13 @@ func TestContradictoryOptionsAreRejected(t *testing.T) { {[]string{"--simple", "--json"}, "incompatible options 'simple' and 'json'"}, {[]string{"--simple", "--csv"}, "incompatible options 'simple' and 'csv'"}, {[]string{"--simple", "--json-stream"}, "incompatible options 'simple' and 'json-stream'"}, + // the short forms name the same options + {[]string{"-4", "-6"}, "incompatible options 'ipv4' and 'ipv6'"}, + // of several pairs one is named + {[]string{"--ipv4", "--ipv6", "--secure", "--insecure"}, "incompatible options 'ipv4' and 'ipv6'"}, + // these two were rejected before, in the same words + {[]string{"--json-stream", "--json"}, "incompatible options 'json-stream' and 'json'"}, + {[]string{"--json-stream", "--csv"}, "incompatible options 'json-stream' and 'csv'"}, } for _, c := range cases { t.Run(strings.Join(c.options, " "), func(t *testing.T) { diff --git a/defs/pinger_test.go b/defs/pinger_test.go index 4123fa9..c1840bb 100644 --- a/defs/pinger_test.go +++ b/defs/pinger_test.go @@ -42,13 +42,16 @@ func TestNewPingerResolvesWithinTheRequestedFamily(t *testing.T) { // The family was ignored for a name with addresses in both: the name was // resolved before the family was set. localhost is such a name on most -// systems. Where it has no address in a family, there is nothing to tell -// apart, and that family is skipped. +// systems. Where it has no address in a family, the pinger must say so and +// not hand out the address of the other family, as it did. func TestNewPingerResolvesANameWithinTheRequestedFamily(t *testing.T) { for _, network := range []string{"ip4", "ip6"} { t.Run(network, func(t *testing.T) { if _, err := net.ResolveIPAddr(network, "localhost"); err != nil { - t.Skipf("localhost has no %s address here: %v", network, err) + if p, err := newPinger("localhost", network); err == nil { + t.Errorf("resolved to %v over %s, where localhost has no such address", p.IPAddr(), network) + } + return } p, err := newPinger("localhost", network) diff --git a/defs/server.go b/defs/server.go index f25b0a8..e72b99d 100644 --- a/defs/server.go +++ b/defs/server.go @@ -227,9 +227,10 @@ func (s *Server) ICMPPingAndJitter(count int, srcIp, network string) (float64, f return rttMillis(stats.AvgRtt), jitter, nil } -// newPinger returns a pinger for host, resolved within network ("ip", "ip4" -// or "ip6"). The network is set before resolving: probing.NewPinger resolves -// at once with "ip", and a pinger that has an address does not resolve again. +// newPinger returns a pinger for host, resolved within network: "ip4" or +// "ip6" for that family, and anything else for either. The network is set +// before resolving: probing.NewPinger resolves at once with "ip", and a +// pinger that has an address does not resolve again. func newPinger(host, network string) (*probing.Pinger, error) { p := probing.New(host) p.SetNetwork(network) diff --git a/options_test.go b/options_test.go index b1f122a..aff6067 100644 --- a/options_test.go +++ b/options_test.go @@ -1,6 +1,10 @@ package main import ( + "encoding/pem" + "net" + "net/http" + "net/http/httptest" "os" "path/filepath" "strings" @@ -32,6 +36,20 @@ func TestUploadSizeOutOfRangeIsRejected(t *testing.T) { }) } + // The largest size passes. Its server takes the connection and never + // answers, so the run ends at the probe and does not get to an upload + // of 2 GiB. The listener stays open, so nothing else can get its port. + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + silent := writeServerList(t, listedServer{1, "Silent", "http://" + ln.Addr().String(), "empty.php"}) + r := runCLI(t, "--local-json", silent, "--server", "1", "--duration", "1", "--timeout", "1", "--no-icmp", "--no-download", "--json", "--upload-size", "2097151") + if msg := r.failure(t); r.code != 1 || !strings.Contains(msg, "is not responding") { + t.Errorf("with the largest size: exit status %d and error %q, want 1 and the silent server reported", r.code, msg) + } + // a run that does not upload, or allocates no payload, does not care for _, unused := range []string{"--no-upload", "--no-pre-allocate"} { if r := runCLI(t, append(args, unused, "--upload-size", "0")...); r.code != 0 { @@ -67,3 +85,33 @@ func TestCACertFileWithoutACertificateIsRejected(t *testing.T) { t.Errorf("with --skip-cert-verify: exit status %d, want 0, stderr:\n%s", r.code, r.stderr) } } + +// A file with a certificate in it is the trust store, whatever else it +// holds: a block that is no certificate next to it does not get the file +// refused, and the run trusts the server the certificate is for. +func TestCACertFileWithACertificateIsUsed(t *testing.T) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/getIP.php" { + w.Write([]byte(`{"processedString":"127.0.0.1 - localhost","rawIspInfo":""}`)) + } + })) + t.Cleanup(ts.Close) + list := writeServerList(t, listedServer{1, "Up", ts.URL, "empty.php"}) + + notACertificate := "-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----\n" + certificate := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ts.Certificate().Raw}) + bundle := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(bundle, append([]byte(notACertificate), certificate...), 0o644); err != nil { + t.Fatalf("write the bundle: %v", err) + } + + args := []string{"--local-json", list, "--server", "1", "--duration", "1", "--no-icmp", "--no-download", "--no-upload", "--json"} + + // without the file the server's certificate comes from an unknown authority + if r := runCLI(t, args...); r.code != 1 || !strings.Contains(r.failure(t), "certificate") { + t.Errorf("without --ca-cert: exit status %d, want 1 for the certificate, stderr:\n%s", r.code, r.stderr) + } + if r := runCLI(t, append(args, "--ca-cert", bundle)...); r.code != 0 { + t.Errorf("with --ca-cert: exit status %d, want 0, stderr:\n%s", r.code, r.stderr) + } +} diff --git a/speedtest/dialer_linux_test.go b/speedtest/dialer_linux_test.go index 2c988fd..2593b4a 100644 --- a/speedtest/dialer_linux_test.go +++ b/speedtest/dialer_linux_test.go @@ -5,11 +5,12 @@ import ( "net" "syscall" "testing" + "time" ) // A connection that cannot be bound to the interface must fail for that -// reason. Setting the mark afterwards must not replace the error, whether the -// mark itself succeeds (as root) or fails (without the privilege for it). +// reason, with or without a mark. The mark is not set once the binding has +// failed, so it cannot replace the error. func TestInterfaceThatCannotBeBoundFailsTheDialDespiteTheMark(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -59,3 +60,91 @@ func TestMarkedDialerKeepsTheSourceAddress(t *testing.T) { t.Error("the dialer does not set the mark") } } + +// What counts is where the connection comes from and what its socket +// carries. The dialer that boundDialer returns has to connect from the +// source address it was given, whether it sets a mark or binds to an +// interface, and the mark has to be on the socket. Setting a mark needs a +// privilege that a test run usually does not have, and that case is then +// skipped. So is the interface case on a kernel that wants a privilege for +// the binding as well. +func TestBoundDialerConnectsFromTheSourceAddress(t *testing.T) { + const source = "127.0.0.2" + + for _, tc := range []struct { + name string + iface string + fwmark int + }{ + {"with a mark", "", 7}, + {"bound to the loopback interface", "lo", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + + from := make(chan string, 1) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + host, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) + conn.Close() + from <- host + }() + + dialer, err := boundDialer(&net.Dialer{LocalAddr: &net.TCPAddr{IP: net.ParseIP(source)}}, tc.iface, tc.fwmark) + if err != nil { + t.Fatalf("boundDialer: %v", err) + } + conn, err := dialer.Dial("tcp", ln.Addr().String()) + if errors.Is(err, syscall.EPERM) { + t.Skipf("not permitted here: %v", err) + } + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + + if tc.fwmark != 0 { + if got := socketMark(t, conn); got != tc.fwmark { + t.Errorf("the socket carries mark %d, want %d", got, tc.fwmark) + } + } + + select { + case got := <-from: + if got != source { + t.Errorf("the connection came from %s, want %s", got, source) + } + case <-time.After(5 * time.Second): + t.Fatal("the connection was not accepted") + } + }) + } +} + +// socketMark reads the mark back from the socket of a connection. +func socketMark(t *testing.T, conn net.Conn) int { + t.Helper() + + raw, err := conn.(*net.TCPConn).SyscallConn() + if err != nil { + t.Fatalf("SyscallConn: %v", err) + } + var mark int + var errSock error + if err := raw.Control(func(fd uintptr) { + mark, errSock = syscall.GetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK) + }); err != nil { + t.Fatalf("Control: %v", err) + } + if errSock != nil { + t.Fatalf("reading the mark: %v", errSock) + } + return mark +} From 9cbe9056e106aa635b8d6666d3ca262ece7c15c3 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Mon, 23 Nov 2026 13:39:32 +0100 Subject: [PATCH 2/4] fix: do not fail --list over an upload size it does not use The size was checked before the servers were listed, so --list with --upload-size out of range ended in a usage error although nothing is uploaded. --- options_test.go | 6 ++++++ speedtest/speedtest.go | 5 +++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/options_test.go b/options_test.go index aff6067..abf9cb8 100644 --- a/options_test.go +++ b/options_test.go @@ -56,6 +56,12 @@ func TestUploadSizeOutOfRangeIsRejected(t *testing.T) { t.Errorf("with %s: exit status %d, want 0, stderr:\n%s", unused, r.code, r.stderr) } } + + // and neither does one that only lists the servers + r = runCLI(t, "--local-json", list, "--list", "--upload-size", "0") + if r.code != 0 || !strings.Contains(r.stdout, "1: Up") { + t.Errorf("with --list: exit status %d and stdout %q, want 0 and the server listed, stderr:\n%s", r.code, r.stdout, r.stderr) + } } // A --ca-cert file with no certificate in it leaves nothing to trust. Say so diff --git a/speedtest/speedtest.go b/speedtest/speedtest.go index c7e43a7..288db28 100644 --- a/speedtest/speedtest.go +++ b/speedtest/speedtest.go @@ -188,8 +188,9 @@ func SpeedTest(c *cli.Context) error { } // The upload payload is allocated in one piece of that many KiB. The - // size is not used where there is no upload, or no payload to allocate. - if size := c.Int(defs.OptionUploadSize); !c.Bool(defs.OptionNoUpload) && !c.Bool(defs.OptionNoPreAllocate) { + // size is not used where there is no upload or no payload to allocate, + // and neither where the run only lists the servers. + if size := c.Int(defs.OptionUploadSize); !c.Bool(defs.OptionNoUpload) && !c.Bool(defs.OptionNoPreAllocate) && !c.Bool(defs.OptionList) { switch { case size < 1: output.WriteError("Upload size cannot be lower than 1 KiB: %d is given\n", size) From d641fab1057c399a7d27665f41f8f475c23bce23 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Mon, 23 Nov 2026 13:39:32 +0100 Subject: [PATCH 3/4] fix: report a --ca-cert file that cannot be read like other errors Such a file ended the run through a fatal log line, without the prefix the other errors get. The message for a file without a certificate now says that PEM is expected. --- options_test.go | 67 +++++++++++++++++++++++++++++++++--------- speedtest/speedtest.go | 4 +-- 2 files changed, 55 insertions(+), 16 deletions(-) diff --git a/options_test.go b/options_test.go index abf9cb8..08e8799 100644 --- a/options_test.go +++ b/options_test.go @@ -70,25 +70,64 @@ func TestUploadSizeOutOfRangeIsRejected(t *testing.T) { func TestCACertFileWithoutACertificateIsRejected(t *testing.T) { backend := mockBackend(t) list := writeServerList(t, listedServer{1, "Up", backend.URL, "empty.php"}) + args := []string{"--local-json", list, "--server", "1", "--duration", "1", "--no-icmp", "--no-download", "--no-upload", "--json"} - bundle := filepath.Join(t.TempDir(), "ca.pem") - if err := os.WriteFile(bundle, []byte("not a certificate\n"), 0o644); err != nil { - t.Fatalf("write the bundle: %v", err) - } + for name, content := range map[string]string{ + "empty": "", + "plain text": "not a certificate\n", + "another PEM type": "-----BEGIN PUBLIC KEY-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END PUBLIC KEY-----\n", + "a broken block": "-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----\n", + } { + t.Run(name, func(t *testing.T) { + bundle := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(bundle, []byte(content), 0o644); err != nil { + t.Fatalf("write the bundle: %v", err) + } + r := runCLI(t, append(args, "--ca-cert", bundle)...) - args := []string{"--local-json", list, "--server", "1", "--duration", "1", "--no-icmp", "--no-download", "--no-upload", "--json", "--ca-cert", bundle} - r := runCLI(t, args...) + if r.code != 1 { + t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr) + } + if msg, want := r.failure(t), "no usable PEM certificate found in "+bundle; msg != want { + t.Errorf("error = %q, want %q", msg, want) + } - if r.code != 1 { - t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr) - } - if msg, want := r.failure(t), "no certificate found in "+bundle; msg != want { - t.Errorf("error = %q, want %q", msg, want) + // with verification off the trust store is not used, and + // neither is what the file holds + if r := runCLI(t, append(args, "--ca-cert", bundle, "--skip-cert-verify")...); r.code != 0 { + t.Errorf("with --skip-cert-verify: exit status %d, want 0, stderr:\n%s", r.code, r.stderr) + } + }) } +} - // with verification off the trust store is not used, and neither is the file - if r := runCLI(t, append(args, "--skip-cert-verify")...); r.code != 0 { - t.Errorf("with --skip-cert-verify: exit status %d, want 0, stderr:\n%s", r.code, r.stderr) +// A --ca-cert file that cannot be read ends the run like any other error, +// with the reason, whether the certificates are verified or not. +func TestCACertFileThatCannotBeReadIsReported(t *testing.T) { + backend := mockBackend(t) + list := writeServerList(t, listedServer{1, "Up", backend.URL, "empty.php"}) + args := []string{"--local-json", list, "--server", "1", "--duration", "1", "--no-icmp", "--no-download", "--no-upload", "--json"} + + dir := t.TempDir() + for name, path := range map[string]string{ + "missing": filepath.Join(dir, "missing.pem"), + "a directory": dir, + } { + for mode, verify := range map[string][]string{"verified": nil, "not verified": {"--skip-cert-verify"}} { + t.Run(name+", "+mode, func(t *testing.T) { + r := runCLI(t, append(append(args, "--ca-cert", path), verify...)...) + + 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.Contains(msg, path) { + t.Errorf("error = %q, want it to name %s", msg, path) + } + }) + } } } diff --git a/speedtest/speedtest.go b/speedtest/speedtest.go index 288db28..d9184b8 100644 --- a/speedtest/speedtest.go +++ b/speedtest/speedtest.go @@ -228,13 +228,13 @@ func SpeedTest(c *cli.Context) error { if caCertFileName := c.String(defs.OptionCACert); caCertFileName != "" { caCert, err := os.ReadFile(caCertFileName) if err != nil { - output.Fatal(err) + return err } caCertPool := x509.NewCertPool() // An empty pool would fail every HTTPS request for an unknown // authority, unless verification is off and the pool is not used. if !caCertPool.AppendCertsFromPEM(caCert) && !c.Bool(defs.OptionSkipCertVerify) { - return fmt.Errorf("no certificate found in %s", caCertFileName) + return fmt.Errorf("no usable PEM certificate found in %s", caCertFileName) } transport.TLSClientConfig = &tls.Config{ From a4c68901a96482d3f90d851cc8e21d0c50a1ea56 Mon Sep 17 00:00:00 2001 From: Josef Schlehofer Date: Mon, 23 Nov 2026 13:39:32 +0100 Subject: [PATCH 4/4] refactor: set the upload size only where the payload is allocated With --no-pre-allocate the size is not checked and not used, and scaling it to bytes could overflow on a 32-bit system. --- defs/server.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/defs/server.go b/defs/server.go index e72b99d..75634a8 100644 --- a/defs/server.go +++ b/defs/server.go @@ -509,13 +509,13 @@ func (s *Server) Upload(noPrealloc, silent, useBytes, useMebi bool, requests int counter := NewCounter() counter.SetMebi(useMebi) - counter.SetUploadSize(uploadSize) if noPrealloc { output.WriteUI("Pre-allocation is disabled, performance might be lower!\n") } else { - // each request reads from this shared payload; without it they stream - // straight from crypto/rand instead + // Each request reads from this shared payload. Without it they + // stream straight from crypto/rand instead, and the size is not used. + counter.SetUploadSize(uploadSize) counter.GenerateBlob() }