Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"os"
"path/filepath"
"strings"
"testing"
)

// An upload size that is not positive or is beyond the limit is a usage
// error. A negative one, or one too large to allocate, used to end in a Go
// panic once the upload test started.
func TestUploadSizeOutOfRangeIsRejected(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", "--json"}

// 2097152 KiB is 2 GiB, the first size past the limit
for _, size := range []string{"-1", "0", "2097152"} {
t.Run("size="+size, func(t *testing.T) {
r := runCLI(t, append(args, "--upload-size", size)...)

if r.code != 1 {
t.Errorf("exit status %d, want 1, stderr:\n%s", r.code, r.stderr)
}
if strings.Contains(r.stderr, "panic") {
t.Errorf("the CLI panicked:\n%s", r.stderr)
}
if msg, want := r.failure(t), "invalid upload size setting"; msg != want {
t.Errorf("error = %q, want %q", msg, want)
}
})
}

// 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 {
t.Errorf("with %s: exit status %d, want 0, stderr:\n%s", unused, r.code, r.stderr)
}
}
}

// A --ca-cert file with no certificate in it leaves nothing to trust. Say so
// at once instead of failing every HTTPS request later for an unknown
// authority.
func TestCACertFileWithoutACertificateIsRejected(t *testing.T) {
backend := mockBackend(t)
list := writeServerList(t, listedServer{1, "Up", backend.URL, "empty.php"})

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)
}

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 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 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)
}
}
61 changes: 61 additions & 0 deletions speedtest/dialer_linux_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package speedtest

import (
"errors"
"net"
"syscall"
"testing"
)

// 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).
func TestInterfaceThatCannotBeBoundFailsTheDialDespiteTheMark(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer ln.Close()

// dial through an interface that does not exist and return why it failed
dial := func(fwmark int) syscall.Errno {
dialer, err := newDialerInterfaceOrFwmarkBound("nosuchif0", fwmark)
if err != nil {
t.Fatalf("newDialerInterfaceOrFwmarkBound: %v", err)
}
conn, err := dialer.Dial("tcp", ln.Addr().String())
if err == nil {
conn.Close()
t.Fatalf("mark %d: connected although the interface does not exist", fwmark)
}
var errno syscall.Errno
if !errors.As(err, &errno) {
t.Fatalf("mark %d: error = %v, want the one from the socket option", fwmark, err)
}
return errno
}

// What the binding alone answers depends on the kernel and on the
// privileges, so that is the reference and not a fixed error.
binding := dial(0)
if withMark := dial(1); withMark != binding {
t.Errorf("error = %v with a mark, want the one from the binding: %v", withMark, binding)
}
}

// --source can be combined with --fwmark. The dialer that sets the mark has
// to keep the source address.
func TestMarkedDialerKeepsTheSourceAddress(t *testing.T) {
source := &net.Dialer{LocalAddr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1")}}

dialer, err := boundDialer(source, "", 7)
if err != nil {
t.Fatalf("boundDialer: %v", err)
}
if dialer.LocalAddr != source.LocalAddr {
t.Errorf("LocalAddr = %v, want the source address %v", dialer.LocalAddr, source.LocalAddr)
}
if dialer.Control == nil {
t.Error("the dialer does not set the mark")
}
}
74 changes: 55 additions & 19 deletions speedtest/speedtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"math"
"net"
"net/http"
"net/url"
Expand All @@ -33,6 +34,12 @@ const (
defaultTelemetryPath = "/results/telemetry.php"
defaultTelemetryShare = "/results/"

// maxUploadSize is the largest --upload-size, in KiB: the most whose
// byte count fits an int on a 32-bit system, just under 2 GiB. The same
// limit holds everywhere, so an option value works on one system if it
// works on another.
maxUploadSize = math.MaxInt32 / 1024

forceNothing = 0
forceHttps = 1
forceHttp = 2
Expand Down Expand Up @@ -165,6 +172,19 @@ func SpeedTest(c *cli.Context) error {
return errors.New("invalid concurrent requests setting")
}

// 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) {
switch {
case size < 1:
output.WriteError("Upload size cannot be lower than 1 KiB: %d is given\n", size)
return errors.New("invalid upload size setting")
case size > maxUploadSize:
output.WriteError("Upload size cannot be more than %d KiB: %d is given\n", maxUploadSize, size)
return errors.New("invalid upload size setting")
}
}

noICMP := c.Bool(defs.OptionNoICMP)

// HTTP requests timeout
Expand Down Expand Up @@ -195,7 +215,11 @@ func SpeedTest(c *cli.Context) error {
output.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// 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)
}

transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: c.Bool(defs.OptionSkipCertVerify),
Expand Down Expand Up @@ -226,7 +250,7 @@ func SpeedTest(c *cli.Context) error {

if iface != "" || fwmark > 0 {
var err error
dialer, err = newDialerInterfaceOrFwmarkBound(iface, fwmark)
dialer, err = boundDialer(dialer, iface, fwmark)
if err != nil {
return err
}
Expand Down Expand Up @@ -322,9 +346,6 @@ func SpeedTest(c *cli.Context) error {
var wg sync.WaitGroup
jobs := make(chan PingJob, len(servers))
results := make(chan PingResult, len(servers))
done := make(chan struct{})

pingList := make(map[int]float64)

// spawn 10 concurrent pingers
for i := 0; i < 10; i++ {
Expand All @@ -338,20 +359,7 @@ func SpeedTest(c *cli.Context) error {
}
close(jobs)

go func() {
wg.Wait()
close(done)
}()

Loop:
for {
select {
case result := <-results:
pingList[result.Index] = result.Ping
case <-done:
break Loop
}
}
pingList := collectPings(results, &wg)

if len(pingList) == 0 {
output.Fatal("No server is currently available, please try again later.")
Expand All @@ -376,6 +384,22 @@ func SpeedTest(c *cli.Context) error {
}
}

// collectPings gathers the ping of every server that answered. It reads the
// results until the workers are done and the channel is closed, so a result
// that is still in the channel when the last worker finishes is not lost.
func collectPings(results chan PingResult, wg *sync.WaitGroup) map[int]float64 {
go func() {
wg.Wait()
close(results)
}()

pingList := make(map[int]float64)
for result := range results {
pingList[result.Index] = result.Ping
}
return pingList
}

func pingWorker(jobs <-chan PingJob, results chan<- PingResult, wg *sync.WaitGroup, srcIp, network string, noICMP bool) {
for job := range jobs {
server := job.Server
Expand Down Expand Up @@ -553,6 +577,18 @@ func contains(arr []int, val int) bool {
return false
}

// boundDialer returns a dialer bound to iface and marked with fwmark. It
// keeps the source address of the dialer given: --source can be combined
// with --fwmark.
func boundDialer(dialer *net.Dialer, iface string, fwmark int) (*net.Dialer, error) {
bound, err := newDialerInterfaceOrFwmarkBound(iface, fwmark)
if err != nil {
return nil, err
}
bound.LocalAddr = dialer.LocalAddr
return bound, nil
}

func newDialerAddressBound(src string, network string) (dialer *net.Dialer, err error) {
// first we parse the IP to see if it's valid
addr, err := net.ResolveIPAddr(network, src)
Expand Down
27 changes: 26 additions & 1 deletion speedtest/speedtest_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package speedtest

import "testing"
import (
"sync"
"testing"
)

func TestWellKnownServerURL(t *testing.T) {
cases := []struct {
Expand Down Expand Up @@ -48,3 +51,25 @@ func TestWellKnownServerURL(t *testing.T) {
})
}
}

// The workers can all be done while their results still wait in the channel.
// Those results count like any other: one of them may be the fastest server.
func TestCollectPingsKeepsTheResultsOfWorkersThatAreDone(t *testing.T) {
// far more than a real list has, so that collecting them takes long
// enough for the "all done" signal to arrive in the middle
const servers = 5000

for round := 0; round < 20; round++ {
var wg sync.WaitGroup
results := make(chan PingResult, servers)
for i := 0; i < servers; i++ {
wg.Add(1)
results <- PingResult{Index: i, Ping: float64(i + 1)}
wg.Done()
}

if got := len(collectPings(results, &wg)); got != servers {
t.Fatalf("collected %d of %d results", got, servers)
}
}
}
3 changes: 2 additions & 1 deletion speedtest/util_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ func newDialerInterfaceOrFwmarkBound(iface string, fwmark int) (dialer *net.Dial
errSock = unix.BindToDevice(int(fd), iface)
}

if fwmark > 0 {
// a mark that could be set must not hide a binding that failed
if fwmark > 0 && errSock == nil {
errSock = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, fwmark)
}
}))
Expand Down