├── .vscode └── settings.json ├── PULL_REQUEST_TEMPLATE.md ├── scripts ├── clean.sh └── cross-compile.sh ├── internal ├── testing_assets │ ├── random750x750.jpg │ └── sthttp_test_config.xml ├── speedtests │ ├── speedtests_test.go │ └── speedtests.go ├── misc │ ├── misc.go │ └── misc_test.go ├── print │ ├── print_test.go │ └── print.go ├── coords │ ├── coords.go │ └── coords_test.go └── sthttp │ ├── sthttp_test.go │ └── sthttp.go ├── speedtest.code-workspace ├── .gitignore ├── Dockerfile ├── .travis.yml ├── COPYING ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── cmd └── speedtest │ ├── main_test.go │ └── main.go ├── CONTRIBUTING.md ├── Gopkg.toml ├── Makefile ├── CODE_OF_CONDUCT.md ├── Gopkg.lock ├── README.md └── LICENSE /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /scripts/clean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | rm -f -v bin/speedtest* 3 | rm -f -v coverage-all.out 4 | rm -f -v coverage.out 5 | -------------------------------------------------------------------------------- /internal/testing_assets/random750x750.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zpeters/speedtest/HEAD/internal/testing_assets/random750x750.jpg -------------------------------------------------------------------------------- /speedtest.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": {} 8 | } 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.exe 3 | bin/ 4 | pkg/ 5 | \#*\# 6 | .\#* 7 | .vagrant/ 8 | Godeps/_workspace 9 | vendor/ 10 | coverage-all.out 11 | coverage.out 12 | -------------------------------------------------------------------------------- /internal/speedtests/speedtests_test.go: -------------------------------------------------------------------------------- 1 | package speedtests 2 | 3 | import "testing" 4 | 5 | func EmptyTest(t *testing.T) { 6 | t.Logf("Empty test...\n") 7 | } 8 | -------------------------------------------------------------------------------- /internal/misc/misc.go: -------------------------------------------------------------------------------- 1 | package misc 2 | 3 | import ( 4 | "math/rand" 5 | "strconv" 6 | ) 7 | 8 | // ToFloat is a shortcut to parse float 9 | func ToFloat(s string) float64 { 10 | f, _ := strconv.ParseFloat(s, 64) 11 | return f 12 | } 13 | 14 | // Urandom produces a random stream of bytes 15 | func Urandom(n int) []byte { 16 | b := make([]byte, n) 17 | for i := 0; i < n; i++ { 18 | b[i] = byte(rand.Int31()) 19 | } 20 | 21 | return b 22 | } 23 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.10 AS builder 2 | 3 | ADD https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 /usr/bin/dep 4 | RUN chmod +x /usr/bin/dep 5 | 6 | WORKDIR $GOPATH/src/github.com/zpeters/speedtest 7 | COPY Gopkg.toml Gopkg.lock ./ 8 | RUN dep ensure --vendor-only 9 | COPY . ./ 10 | RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /app ./cmd/speedtest 11 | 12 | FROM scratch 13 | COPY --from=builder /app ./ 14 | ENTRYPOINT ["./app"] 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: true 3 | go: 4 | - 1.9 5 | before_install: 6 | - sudo apt-get update -y 7 | - sudo apt install curl -y 8 | - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 9 | install: 10 | - dep ensure 11 | - make test 12 | script: 13 | - go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest ./cmd/speedtest 14 | - ./bin/speedtest -p 15 | notifications: 16 | email: 17 | recipients: 18 | - zpeters@gmail.com 19 | on_failure: always 20 | on_success: always 21 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | This program is free software: you can redistribute it and/or modify 2 | it under the terms of the GNU General Public License as published by 3 | the Free Software Foundation, either version 3 of the License, or 4 | (at your option) any later version. 5 | 6 | This program is distributed in the hope that it will be useful, 7 | but WITHOUT ANY WARRANTY; without even the implied warranty of 8 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 9 | GNU General Public License for more details. 10 | 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /cmd/speedtest/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/spf13/viper" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestInit(t *testing.T) { 11 | t.Parallel() 12 | assert.NotNil(t, viper.GetBool("debug")) 13 | assert.NotNil(t, viper.GetBool("quiet")) 14 | assert.NotNil(t, viper.GetBool("report")) 15 | assert.NotEmpty(t, viper.GetInt("numclosest")) 16 | assert.NotEmpty(t, viper.GetInt("numlatencytests")) 17 | assert.NotEmpty(t, viper.GetString("reportchar")) 18 | assert.NotEmpty(t, viper.GetString("algotype")) 19 | assert.NotEmpty(t, viper.GetInt("httptimeout")) 20 | assert.NotEmpty(t, viper.Get("dlsizes").([]int)) 21 | assert.NotEmpty(t, viper.Get("ulsizes").([]int)) 22 | } 23 | -------------------------------------------------------------------------------- /internal/print/print_test.go: -------------------------------------------------------------------------------- 1 | package print 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/urfave/cli" 7 | "github.com/zpeters/speedtest/internal/sthttp" 8 | ) 9 | 10 | func TestServer(t *testing.T) { 11 | s := sthttp.Server{} 12 | s.ID = "123" 13 | s.Sponsor = "Sponsor" 14 | s.Name = "Name" 15 | s.Country = "Country" 16 | 17 | Server(s) 18 | } 19 | 20 | func TestEnvironmentReport(t *testing.T) { 21 | stc := sthttp.Client{ 22 | Config: &sthttp.Config{}, 23 | SpeedtestConfig: &sthttp.SpeedtestConfig{}, 24 | HTTPConfig: &sthttp.HTTPConfig{}, 25 | } 26 | app := cli.NewApp() 27 | app.Action = func(c *cli.Context) error { 28 | EnvironmentReport(&stc) 29 | return nil 30 | } 31 | app.Run([]string{"testing"}) 32 | } 33 | -------------------------------------------------------------------------------- /internal/misc/misc_test.go: -------------------------------------------------------------------------------- 1 | package misc 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | type ToFloatTest struct { 9 | in string 10 | out float64 11 | } 12 | 13 | var ToFloatTests = []ToFloatTest{ 14 | {"1.00", 1.00}, 15 | {"100", 100.00}, 16 | {"123.123457843274", 123.123457843274}, 17 | } 18 | 19 | func TestToFloat(t *testing.T) { 20 | for i, test := range ToFloatTests { 21 | output := ToFloat(test.in) 22 | if output != test.out { 23 | t.Errorf("#%d: Input %s; want %f, got %f", i, test.in, test.out, output) 24 | } 25 | } 26 | } 27 | 28 | func TestUrandom(t *testing.T) { 29 | input := 123 30 | output := Urandom(input) 31 | 32 | typ := reflect.TypeOf(output) 33 | if typ.Kind() != reflect.Slice { 34 | t.Errorf("Not a slice: %s\n", typ.Kind()) 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Desktop (please complete the following information):** 24 | - OS: [e.g. iOS] 25 | - Browser [e.g. chrome, safari] 26 | - Version [e.g. 22] 27 | 28 | **Smartphone (please complete the following information):** 29 | - Device: [e.g. iPhone6] 30 | - OS: [e.g. iOS8.1] 31 | - Browser [e.g. stock browser, safari] 32 | - Version [e.g. 22] 33 | 34 | **Additional context** 35 | Add any other context about the problem here. 36 | -------------------------------------------------------------------------------- /internal/coords/coords.go: -------------------------------------------------------------------------------- 1 | package coords 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | // RadiusEarth is the radius of the Earth 8 | const RadiusEarth = 6372.8 9 | 10 | // Coordinate on the Earth 11 | type Coordinate struct { 12 | Lat float64 13 | Lon float64 14 | } 15 | 16 | // Pos is a coordinate in radians 17 | type Pos struct { 18 | φ float64 // latitude, radians 19 | ψ float64 // longitude, radians 20 | } 21 | 22 | // Great Circle 23 | // http://rosettacode.org/wiki/Haversine_formula#Go 24 | func haversine(θ float64) float64 { 25 | return .5 * (1 - math.Cos(θ)) 26 | } 27 | 28 | // DegPos returns (radians) from lat and lon 29 | func DegPos(lat, lon float64) Pos { 30 | return Pos{lat * math.Pi / 180, lon * math.Pi / 180} 31 | } 32 | 33 | // HsDist is the distance from two positions using the great circle formula 34 | func HsDist(p1, p2 Pos) float64 { 35 | return 2 * RadiusEarth * math.Asin(math.Sqrt(haversine(p2.φ-p1.φ)+ 36 | math.Cos(p1.φ)*math.Cos(p2.φ)*haversine(p2.ψ-p1.ψ))) 37 | } 38 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## GitHub Workflow 2 | 3 | Developing patches should follow this workflow: 4 | 5 | ### Initial Setup 6 | 7 | 1. Fork on GitHub (click Fork button). This creates your own working copy on github. 8 | 2. Clone to computer: `git clone git@github.com:<>/speedtest.git` 9 | 3. cd into your repo: `cd speedtest` 10 | 4. Set up remote upstream: `git remote add -f upstream git://github.com/zpeters/speedtest.git` 11 | 12 | ### Adding a Feature 13 | 14 | 1. Create a branch for the new feature: `git checkout -b my_new_feature` 15 | 2. Work on your feature, add and commit as usual 16 | 17 | Creating a branch is not strictly necessary, but it makes it easy to delete your branch when the feature has been merged into upstream, diff your branch with the version that actually ended in upstream, and to submit pull requests for multiple features (branches). 18 | 19 | ### Pushing to GitHub 20 | 21 | 8. Push branch to GitHub: `git push origin my_new_feature` 22 | 9. Issue pull request: Click Pull Request button on GitHub -------------------------------------------------------------------------------- /scripts/cross-compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | VERSION=$(git describe --tags --always) 3 | 4 | 5 | echo "Building darwin-amd64..." 6 | GOOS="darwin" GOARCH="amd64" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-mac-amd64-${VERSION} ./cmd/speedtest 7 | 8 | echo "Building windows-386..." 9 | GOOS="windows" GOARCH="386" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-32-${VERSION}.exe ./cmd/speedtest 10 | 11 | echo "Building windows-amd64..." 12 | GOOS="windows" GOARCH="amd64" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-64-${VERSION}.exe ./cmd/speedtest 13 | 14 | echo "Building freebsd-386..." 15 | GOOS="freebsd" GOARCH="386" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-freebsd-386-${VERSION} ./cmd/speedtest 16 | 17 | echo "Building linux-arm..." 18 | GOOS="linux" GOARCH="arm" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-linux-arm-${VERSION} ./cmd/speedtest 19 | 20 | echo "Building linux-386..." 21 | GOOS="linux" GOARCH="386" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-linux-386-${VERSION} ./cmd/speedtest 22 | 23 | echo "Building linux-amd64..." 24 | GOOS="linux" GOARCH="amd64" go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-linux-amd64-${VERSION} ./cmd/speedtest 25 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | branch = "master" 30 | name = "github.com/dchest/uniuri" 31 | 32 | [[constraint]] 33 | name = "github.com/google/go-github" 34 | version = "15.0.0" 35 | 36 | [[constraint]] 37 | name = "github.com/spf13/viper" 38 | version = "1.0.2" 39 | 40 | [[constraint]] 41 | name = "github.com/stretchr/testify" 42 | version = "1.2.1" 43 | 44 | [[constraint]] 45 | name = "github.com/urfave/cli" 46 | version = "1.20.0" 47 | 48 | [prune] 49 | go-tests = true 50 | unused-packages = true 51 | 52 | [[constraint]] 53 | name = "github.com/smartystreets/goconvey" 54 | version = "1.6.3" 55 | -------------------------------------------------------------------------------- /internal/print/print.go: -------------------------------------------------------------------------------- 1 | package print 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "runtime" 8 | 9 | "github.com/zpeters/speedtest/internal/sthttp" 10 | ) 11 | 12 | // Server prints the results in "human" format 13 | func Server(server sthttp.Server) { 14 | fmt.Printf("%-4s | %s (%s, %s)\n", server.ID, server.Sponsor, server.Name, server.Country) 15 | } 16 | 17 | // EnvironmentReport is a debugging report helpful for debugging 18 | func EnvironmentReport(client *sthttp.Client) { 19 | log.Printf("Env Report") 20 | log.Printf("-------------------------------\n") 21 | log.Printf("[User Environment]\n") 22 | log.Printf("Arch: %v\n", runtime.GOARCH) 23 | log.Printf("OS: %v\n", runtime.GOOS) 24 | log.Printf("IP: %v\n", client.Config.IP) 25 | log.Printf("Lat: %v\n", client.Config.Lat) 26 | log.Printf("Lon: %v\n", client.Config.Lon) 27 | log.Printf("ISP: %v\n", client.Config.Isp) 28 | log.Printf("Config: %s\n", client.SpeedtestConfig.ConfigURL) 29 | log.Printf("Servers: %s\n", client.SpeedtestConfig.ServersURL) 30 | log.Printf("User Agent: %s\n", client.SpeedtestConfig.UserAgent) 31 | log.Printf("HTTP Timeout (seconds): %d\n", client.HTTPConfig.HTTPTimeout/1000000000) 32 | log.Printf("-------------------------------\n") 33 | log.Printf("[args]\n") 34 | log.Printf("%#v\n", os.Args) 35 | log.Printf("--------------------------------\n") 36 | } 37 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile for Go 3 | # 4 | SHELL=/usr/bin/env bash 5 | VERSION=$(shell git describe --tags --always) 6 | PACKAGES = $(shell find ./ -type d | grep -v 'vendor' | grep -v '.git' | grep -v 'bin') 7 | 8 | .PHONY: list 9 | .PHONY: test-cover-html 10 | 11 | default: build 12 | 13 | dockerbuild: 14 | docker build -t speedtest . 15 | 16 | dockerrun: 17 | docker run --rm -it speedtest 18 | 19 | dockerclean: 20 | docker-clean all 21 | 22 | build: 23 | go build -ldflags="-X main.Version=${VERSION}" -o bin/speedtest-${VERSION} ./cmd/speedtest 24 | 25 | static: 26 | CGO_ENABLED=0 GOOS=linux go build -a -ldflags="-extldflags \"static\" -s -w" -o bin/speedtest ./cmd/speedtest 27 | upx bin/speedtest 28 | 29 | clean: 30 | scripts/clean.sh 31 | 32 | vet: 33 | go vet ./cmd/... 34 | go vet ./internal/... 35 | 36 | lint: 37 | golint ./cmd/... 38 | golint ./internal/... 39 | 40 | fmt: 41 | gofmt -w ./cmd/speedtest 42 | gofmt -w ./internal/coords 43 | gofmt -w ./internal/misc 44 | gofmt -w ./internal/print 45 | gofmt -w ./internal/sthttp 46 | gofmt -w ./internal/speedtests 47 | 48 | test: 49 | go test ./cmd/... ./internal/... 50 | 51 | cover: 52 | go test -cover ./cmd/... ./internal/... 53 | 54 | coverage: 55 | echo "mode: count" > coverage-all.out 56 | $(foreach pkg,$(PACKAGES),\ 57 | go test -coverprofile=coverage.out -covermode=count $(pkg);\ 58 | tail -n +2 coverage.out >> coverage-all.out;) 59 | go tool cover -html=coverage-all.out 60 | 61 | cross: 62 | scripts/cross-compile.sh 63 | -------------------------------------------------------------------------------- /internal/coords/coords_test.go: -------------------------------------------------------------------------------- 1 | package coords 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type HalversineTest struct { 10 | in float64 11 | out float64 12 | } 13 | 14 | var halversinetests = []HalversineTest{ 15 | {1.00, 0.22984884706593012}, 16 | } 17 | 18 | func TestHalversine(t *testing.T) { 19 | for i, test := range halversinetests { 20 | output := haversine(test.in) 21 | if output != test.out { 22 | t.Errorf("#%d: Input %f; want %f, got %f", i, test.in, test.out, output) 23 | } 24 | } 25 | } 26 | 27 | func TestDegPos(t *testing.T) { 28 | type TestExpect struct { 29 | PosLat float64 30 | PosLon float64 31 | Lat float64 32 | Lon float64 33 | } 34 | 35 | tests := []TestExpect{ 36 | {63.506144, 9.20091, 1.1083913080456418, 0.16058617367967148}, 37 | } 38 | 39 | for test := range tests { 40 | res := DegPos(tests[test].PosLat, tests[test].PosLon) 41 | if (res.φ != tests[test].Lat) || (res.ψ != tests[test].Lon) { 42 | t.Logf("Got: %#v\n", res) 43 | t.Errorf("Should be: %#v %#v\n", tests[test].Lat, tests[test].Lon) 44 | } 45 | } 46 | } 47 | 48 | func TestHsDist(t *testing.T) { 49 | type TestExpect struct { 50 | Pos1Lat float64 51 | Pos1Lon float64 52 | Pos2Lat float64 53 | Pos2Lon float64 54 | Distance float64 55 | } 56 | 57 | tests := []TestExpect{ 58 | {0.7102, -1.2923, 0.8527, 0.400, 7174.056241819571}, 59 | } 60 | 61 | for test := range tests { 62 | pos1 := Pos{tests[test].Pos1Lat, tests[test].Pos1Lon} 63 | pos2 := Pos{tests[test].Pos2Lat, tests[test].Pos2Lon} 64 | expect := tests[test].Distance 65 | res := HsDist(pos1, pos2) 66 | assert.Equal(t, res, expect) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at zpeters@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /internal/speedtests/speedtests.go: -------------------------------------------------------------------------------- 1 | package speedtests 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | 8 | "github.com/zpeters/speedtest/internal/misc" 9 | "github.com/zpeters/speedtest/internal/print" 10 | "github.com/zpeters/speedtest/internal/sthttp" 11 | ) 12 | 13 | var ( 14 | // DefaultDLSizes defines the default download sizes 15 | DefaultDLSizes = []int{350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000} 16 | // DefaultULSizes defines the default upload sizes 17 | DefaultULSizes = []int{int(0.25 * 1024 * 1024), int(0.5 * 1024 * 1024), int(1.0 * 1024 * 1024), int(1.5 * 1024 * 1024), int(2.0 * 1024 * 1024)} 18 | ) 19 | 20 | // Tester defines a Speedtester client tester 21 | type Tester struct { 22 | Client *sthttp.Client 23 | DLSizes []int 24 | ULSizes []int 25 | Quiet bool 26 | Report bool 27 | Debug bool 28 | AlgoType string 29 | } 30 | 31 | // NewTester creates a new Tester struct. should probably make 32 | // this more conventional with a "make_tester" or similar 33 | func NewTester(client *sthttp.Client, dlsizes []int, ulsizes []int, quiet bool, report bool) *Tester { 34 | return &Tester{ 35 | Client: client, 36 | DLSizes: dlsizes, 37 | ULSizes: ulsizes, 38 | Quiet: quiet, 39 | Report: report, 40 | } 41 | } 42 | 43 | // Download will perform the "normal" speedtest download test 44 | func (tester *Tester) Download(server sthttp.Server) float64 { 45 | var urls []string 46 | var maxSpeed float64 47 | var avgSpeed float64 48 | 49 | // http://speedtest1.newbreakcommunications.net/speedtest/speedtest/ 50 | for size := range tester.DLSizes { 51 | url := server.URL 52 | splits := strings.Split(url, "/") 53 | baseURL := strings.Join(splits[1:len(splits)-1], "/") 54 | randomImage := fmt.Sprintf("random%dx%d.jpg", tester.DLSizes[size], tester.DLSizes[size]) 55 | downloadURL := "http:/" + baseURL + "/" + randomImage 56 | urls = append(urls, downloadURL) 57 | } 58 | 59 | if !tester.Quiet && !tester.Report { 60 | log.Printf("Testing download speed") 61 | } 62 | 63 | for u := range urls { 64 | if tester.Debug { 65 | log.Printf("Download Test Run: %s\n", urls[u]) 66 | } 67 | dlSpeed, err := tester.Client.DownloadSpeed(urls[u]) 68 | if err != nil { 69 | log.Printf("Can't get download speed") 70 | log.Fatal(err) 71 | } 72 | if !tester.Quiet && !tester.Debug && !tester.Report { 73 | fmt.Printf(".") 74 | } 75 | if tester.Debug { 76 | log.Printf("Dl Speed: %v\n", dlSpeed) 77 | } 78 | 79 | if tester.AlgoType == "max" { 80 | if dlSpeed > maxSpeed { 81 | maxSpeed = dlSpeed 82 | } 83 | } else { 84 | avgSpeed = avgSpeed + dlSpeed 85 | } 86 | } 87 | 88 | if !tester.Quiet && !tester.Report { 89 | fmt.Printf("\n") 90 | } 91 | 92 | if tester.AlgoType != "max" { 93 | return avgSpeed / float64(len(urls)) 94 | } 95 | return maxSpeed 96 | 97 | } 98 | 99 | // Upload runs a "normal" speedtest upload test 100 | func (tester *Tester) Upload(server sthttp.Server) float64 { 101 | // https://github.com/sivel/speedtest-cli/blob/master/speedtest-cli 102 | var ulsize []int 103 | var maxSpeed float64 104 | var avgSpeed float64 105 | 106 | for size := range tester.ULSizes { 107 | ulsize = append(ulsize, tester.ULSizes[size]) 108 | } 109 | 110 | if !tester.Quiet && !tester.Report { 111 | log.Printf("Testing upload speed") 112 | } 113 | 114 | for i := 0; i < len(ulsize); i++ { 115 | if tester.Debug { 116 | log.Printf("Upload Test Run: %v\n", i) 117 | } 118 | r := misc.Urandom(ulsize[i]) 119 | ulSpeed, err := tester.Client.UploadSpeed(server.URL, "text/xml", r) 120 | if err != nil { 121 | log.Fatal(err) 122 | } 123 | if !tester.Quiet && !tester.Debug && !tester.Report { 124 | fmt.Printf(".") 125 | } 126 | if tester.Debug { 127 | log.Printf("Ul Amount: %v bytes\n", len(r)) 128 | log.Printf("Ul Speed: %vMbps\n", ulSpeed) 129 | } 130 | 131 | if tester.AlgoType == "max" { 132 | if ulSpeed > maxSpeed { 133 | maxSpeed = ulSpeed 134 | } 135 | } else { 136 | avgSpeed = avgSpeed + ulSpeed 137 | } 138 | 139 | } 140 | 141 | if !tester.Quiet && !tester.Report { 142 | fmt.Printf("\n") 143 | } 144 | 145 | if tester.AlgoType != "max" { 146 | return avgSpeed / float64(len(ulsize)) 147 | } 148 | return maxSpeed 149 | } 150 | 151 | // FindServer will find a specific server in the servers list 152 | func (tester *Tester) FindServer(id string, serversList []sthttp.Server) sthttp.Server { 153 | var foundServer sthttp.Server 154 | for s := range serversList { 155 | if serversList[s].ID == id { 156 | foundServer = serversList[s] 157 | } 158 | } 159 | if foundServer.ID == "" { 160 | log.Fatalf("Cannot locate server Id '%s' in our list of speedtest servers!\n", id) 161 | } 162 | return foundServer 163 | } 164 | 165 | // ListServers prints a list of all "global" servers 166 | func (tester *Tester) ListServers(configURL string, serversURL string, blacklist []string) (err error) { 167 | if tester.Debug { 168 | fmt.Printf("Loading config from speedtest.net\n") 169 | } 170 | c, err := tester.Client.GetConfig() 171 | if err != nil { 172 | return err 173 | } 174 | tester.Client.Config = &c 175 | 176 | if tester.Debug { 177 | fmt.Printf("\n") 178 | } 179 | 180 | if tester.Debug { 181 | fmt.Printf("Getting servers list...") 182 | } 183 | allServers, err := tester.Client.GetServers() 184 | if err != nil { 185 | log.Fatal(err) 186 | } 187 | if tester.Debug { 188 | fmt.Printf("(%d) found\n", len(allServers)) 189 | } 190 | for s := range allServers { 191 | server := allServers[s] 192 | print.Server(server) 193 | } 194 | return nil 195 | } 196 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" 6 | name = "github.com/davecgh/go-spew" 7 | packages = ["spew"] 8 | pruneopts = "UT" 9 | revision = "346938d642f2ec3594ed81d874461961cd0faa76" 10 | version = "v1.1.0" 11 | 12 | [[projects]] 13 | branch = "master" 14 | digest = "1:fdae1c338ec6667687fb3fdbde842b3c421c930163981b5d441502b240b7f50b" 15 | name = "github.com/dchest/uniuri" 16 | packages = ["."] 17 | pruneopts = "UT" 18 | revision = "8902c56451e9b58ff940bbe5fec35d5f9c04584a" 19 | 20 | [[projects]] 21 | digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" 22 | name = "github.com/fsnotify/fsnotify" 23 | packages = ["."] 24 | pruneopts = "UT" 25 | revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" 26 | version = "v1.4.7" 27 | 28 | [[projects]] 29 | digest = "1:51bee9f1987dcdb9f9a1b4c20745d78f6bf6f5f14ad4e64ca883eb64df4c0045" 30 | name = "github.com/google/go-github" 31 | packages = ["github"] 32 | pruneopts = "UT" 33 | revision = "e48060a28fac52d0f1cb758bc8b87c07bac4a87d" 34 | version = "v15.0.0" 35 | 36 | [[projects]] 37 | branch = "master" 38 | digest = "1:a63cff6b5d8b95638bfe300385d93b2a6d9d687734b863da8e09dc834510a690" 39 | name = "github.com/google/go-querystring" 40 | packages = ["query"] 41 | pruneopts = "UT" 42 | revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a" 43 | 44 | [[projects]] 45 | branch = "master" 46 | digest = "1:a361611b8c8c75a1091f00027767f7779b29cb37c456a71b8f2604c88057ab40" 47 | name = "github.com/hashicorp/hcl" 48 | packages = [ 49 | ".", 50 | "hcl/ast", 51 | "hcl/parser", 52 | "hcl/printer", 53 | "hcl/scanner", 54 | "hcl/strconv", 55 | "hcl/token", 56 | "json/parser", 57 | "json/scanner", 58 | "json/token", 59 | ] 60 | pruneopts = "UT" 61 | revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" 62 | 63 | [[projects]] 64 | digest = "1:5149009cc36718234a9ad2896b04b04716808b8d72143b5687c0a15b53132b27" 65 | name = "github.com/magiconair/properties" 66 | packages = ["."] 67 | pruneopts = "UT" 68 | revision = "c3beff4c2358b44d0493c7dda585e7db7ff28ae6" 69 | version = "v1.7.6" 70 | 71 | [[projects]] 72 | branch = "master" 73 | digest = "1:2514da1e59c0a936d8c1e0fbf5592267a3c5893eb4555ce767bb54d149e9cf6e" 74 | name = "github.com/mitchellh/mapstructure" 75 | packages = ["."] 76 | pruneopts = "UT" 77 | revision = "00c29f56e2386353d58c599509e8dc3801b0d716" 78 | 79 | [[projects]] 80 | digest = "1:7231124c9669dfb54b82ef8b89f2735cf5d5d2529a23c6ac93a8c4b8bbb28b28" 81 | name = "github.com/pelletier/go-toml" 82 | packages = ["."] 83 | pruneopts = "UT" 84 | revision = "acdc4509485b587f5e675510c4f2c63e90ff68a8" 85 | version = "v1.1.0" 86 | 87 | [[projects]] 88 | digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" 89 | name = "github.com/pmezard/go-difflib" 90 | packages = ["difflib"] 91 | pruneopts = "UT" 92 | revision = "792786c7400a136282c1664665ae0a8db921c6c2" 93 | version = "v1.0.0" 94 | 95 | [[projects]] 96 | digest = "1:fe0b7f0c9a5e5511001fe085b0a156b29266012cd984a63e4059a30e84bba03a" 97 | name = "github.com/spf13/afero" 98 | packages = [ 99 | ".", 100 | "mem", 101 | ] 102 | pruneopts = "UT" 103 | revision = "63644898a8da0bc22138abf860edaf5277b6102e" 104 | version = "v1.1.0" 105 | 106 | [[projects]] 107 | digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" 108 | name = "github.com/spf13/cast" 109 | packages = ["."] 110 | pruneopts = "UT" 111 | revision = "8965335b8c7107321228e3e3702cab9832751bac" 112 | version = "v1.2.0" 113 | 114 | [[projects]] 115 | branch = "master" 116 | digest = "1:080e5f630945ad754f4b920e60b4d3095ba0237ebf88dc462eb28002932e3805" 117 | name = "github.com/spf13/jwalterweatherman" 118 | packages = ["."] 119 | pruneopts = "UT" 120 | revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" 121 | 122 | [[projects]] 123 | digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" 124 | name = "github.com/spf13/pflag" 125 | packages = ["."] 126 | pruneopts = "UT" 127 | revision = "583c0c0531f06d5278b7d917446061adc344b5cd" 128 | version = "v1.0.1" 129 | 130 | [[projects]] 131 | digest = "1:59e7dceb53b4a1e57eb1eb0bf9951ff0c25912df7660004a789b62b4e8cdca3b" 132 | name = "github.com/spf13/viper" 133 | packages = ["."] 134 | pruneopts = "UT" 135 | revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" 136 | version = "v1.0.2" 137 | 138 | [[projects]] 139 | digest = "1:f85e109eda8f6080877185d1c39e98dd8795e1780c08beca28304b87fd855a1c" 140 | name = "github.com/stretchr/testify" 141 | packages = ["assert"] 142 | pruneopts = "UT" 143 | revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" 144 | version = "v1.2.1" 145 | 146 | [[projects]] 147 | digest = "1:b24d38b282bacf9791408a080f606370efa3d364e4b5fd9ba0f7b87786d3b679" 148 | name = "github.com/urfave/cli" 149 | packages = ["."] 150 | pruneopts = "UT" 151 | revision = "cfb38830724cc34fedffe9a2a29fb54fa9169cd1" 152 | version = "v1.20.0" 153 | 154 | [[projects]] 155 | branch = "master" 156 | digest = "1:59fdb8bf86a81a5bff0e1a6c39d06f09251c627aeab82d64d3431cf4014d10d7" 157 | name = "golang.org/x/sys" 158 | packages = ["unix"] 159 | pruneopts = "UT" 160 | revision = "6f686a352de66814cdd080d970febae7767857a3" 161 | 162 | [[projects]] 163 | digest = "1:8029e9743749d4be5bc9f7d42ea1659471767860f0cdc34d37c3111bd308a295" 164 | name = "golang.org/x/text" 165 | packages = [ 166 | "internal/gen", 167 | "internal/triegen", 168 | "internal/ucd", 169 | "transform", 170 | "unicode/cldr", 171 | "unicode/norm", 172 | ] 173 | pruneopts = "UT" 174 | revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" 175 | version = "v0.3.0" 176 | 177 | [[projects]] 178 | digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" 179 | name = "gopkg.in/yaml.v2" 180 | packages = ["."] 181 | pruneopts = "UT" 182 | revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" 183 | version = "v2.2.1" 184 | 185 | [solve-meta] 186 | analyzer-name = "dep" 187 | analyzer-version = 1 188 | input-imports = [ 189 | "github.com/dchest/uniuri", 190 | "github.com/google/go-github/github", 191 | "github.com/spf13/viper", 192 | "github.com/stretchr/testify/assert", 193 | "github.com/urfave/cli", 194 | ] 195 | solver-name = "gps-cdcl" 196 | solver-version = 1 197 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2019 Update 2 | ========== 3 | I don't have a lot of time to work on this code anymore. I may post updates from time to time, but at the moment this software is mostly abandonded. I am working on a Rust implementation and will post more details here in the future. See https://github.com/zpeters/speedtestr 4 | 5 | Thank you for all of the fun and support over the years. 6 | 7 | -zach 8 | 9 | 10 | VERSION 2.0 Testing 11 | =================== 12 | Initial testing release of v2.0 is out for the testing. See "releases" for downloads. The current "test" is hard coded and there are no options at the moment. Please send me any feedback at zpeters@gmail.com or through the issues. 13 | 14 | The Unofficial Speedtest CLI 15 | ============================ 16 | The Unofficial Speedtest CLI is a command-line program to test 17 | bandwidth in situations where you don't have access to a full GUI 18 | environment and web browser. 19 | 20 | In [2013 I was feeling guilty](http://thehelpfulhacker.net/2013/07/29/giving-something-back/) 21 | about using Open Source software for most of my life without giving 22 | anything back in return. I decided to create this project to my part 23 | to help the IT community. 24 | 25 | A lot of the initial algorithms here are based on different scripts I 26 | found when I was studying how speedtest.net works. Mainly, @sivel's 27 | [speedtest-cli](https://github.com/sivel/speedtest-cli), 28 | thanks for your work! 29 | 30 | **master branch** 31 | [![Go Report Card](https://goreportcard.com/badge/github.com/zpeters/speedtest)](https://goreportcard.com/report/github.com/zpeters/speedtest) 32 | [![Github All Releases](https://img.shields.io/github/downloads/zpeters/speedtest/total.svg?style=plastic)](https://www.somsubhra.com/github-release-stats/?username=zpeters&repository=speedtest) 33 | [![Build Status](https://travis-ci.org/zpeters/speedtest.svg?branch=master)](https://travis-ci.org/zpeters/speedtest) 34 | [![GoDoc](https://godoc.org/github.com/zpeters/speedtest?status.svg)](https://godoc.org/github.com/zpeters/speedtest) 35 | 36 | **development branch** 37 | [![Build Status](https://travis-ci.org/zpeters/speedtest.svg?branch=develop)](https://travis-ci.org/zpeters/speedtest) 38 | 39 | [![Sparkline](https://stars.medv.io/zpeters/speedtest.svg)](https://stars.medv.io/zpeters/speedtest) 40 | 41 | License 42 | ======= 43 | Licensed under GPLv3 (See COPYING and LICENSE) 44 | 45 | Download 46 | ======== 47 | - Github (Windows/Linux/Mac) - https://github.com/zpeters/speedtest/releases 48 | - Mirror (Windows/Linux/Mac) - http://media.thehelpfulhacker.net/index.php?dir=speedtest/ 49 | 50 | Build 51 | ===== 52 | See [Build Instructions](https://github.com/zpeters/speedtest/wiki/Build-Instructions) 53 | 54 | Bugs, Features and Contributing 55 | ================= 56 | See github issues tracker - https://github.com/zpeters/speedtest/issues 57 | 58 | Usage 59 | ===== 60 | speedtest.exe -- normal run, will automatically select the closests/fastest server to test against 61 | ```shell 62 | $ bin/speedtest.exe 63 | Finding fastest server.. 64 | 1752 | 5NINES (Madison, WI, United States) 65 | Testing download speed...... 66 | Testing upload speed...... 67 | Ping: 53.613233ms | Download: 13.34 Mbps | Upload: 3.89 Mbps 68 | ``` 69 | 70 | speedtest.exe -l -- List servers 71 | ```shell 72 | $ bin/speedtest.exe -l 73 | 1724 | CityNet (Zaporizhzhya, Ukraine) 74 | 2966 | FUSION MEDIA Kft. (Budapest, Hungary) 75 | 3634 | Paul Bunyan Communications (Bemidji, MN, United States 76 | ... 77 | 78 | ``` 79 | 80 | speedtest.exe -s 1724 -- Run against a specific server 81 | ```shell 82 | $ bin/speedtest.exe -s 1724 83 | 1724 | CityNet (Zaporizhzhya, Ukraine) 84 | Testing latency... 85 | Testing download speed...... 86 | Testing upload speed...... 87 | Ping: 982.913566ms | Download: 0.91 Mbps | Upload: 1.25 Mbps 88 | ``` 89 | 90 | speedtest.exe -b 1234 -b 5678 -- Run the test blacklisting servers 1234 and 5678 91 | speedtest.exe -r -- Runs speedtest in "reporting" mode (useful for Labtec, Excel spreadsheets, etc) 92 | speedtest.exe -r -rc="," -- Use a different separator (default is '|') 93 | Report Fields: Server ID, Server Name (Location), Ping time in ms, Download speed in kbps, Upload speed in kbps 94 | ```shell 95 | 1752|5NINES(Madison, WI,United States)|36.18|19452|4053 96 | ``` 97 | 98 | ```shell 99 | COMMANDS: 100 | help, h Shows a list of commands or help for one command 101 | 102 | GLOBAL OPTIONS: 103 | --algo value, -a value Specify the measurement method to use ('max', 'avg') 104 | --debug, -d Turn on debugging 105 | --list, -l List available servers 106 | --update, -u Check for a new version of speedtest 107 | --ping, -p Ping only mode 108 | --quiet, -q Quiet mode 109 | --report, -r Reporting mode output, minimal output with '|' for separators, use '--rc' 110 | to change separator characters. Reports the following: Server ID, 111 | Server Name (Location), Ping time in ms, Download speed in kbps, Upload speed in kbps 112 | --downloadonly, --do Only perform download test 113 | --uploadonly, --uo Only perform upload test 114 | --reportchar value, --rc value Set the report separator. Example: --rc=',' 115 | --server value, -s value Use a specific server 116 | --blacklist value, -b value Blacklist a server. Use this multiple times for more than one server 117 | --mini value, -m value URL of speedtest mini server 118 | --useragent value, --ua value Specify a useragent string 119 | --numclosest value, --nc value Number of 'closest' servers to find (default: 3) 120 | --httptimeout value, -t value Timeout (seconds) for http connections (default: 15) 121 | --numlatency value, --nl value Number of latency tests to perform (default: 5) 122 | --interface value, -I value Source IP address or name of an interface 123 | --help, -h show help 124 | --version, -v print the version 125 | ``` 126 | 127 | Thank You 128 | ========= 129 | - Jacob McDonald - jmc734 - Cleaned up printing and formatting. Added parameter passing to run.sh - https://github.com/zpeters/speedtest/pull/4 130 | - Cory Lievers - Testing and feedback. Suggestions for formatting to make this more useful for labtec - https://github.com/zpeters/speedtest/issues/9 131 | - Paul Baker (Network Manager - BMS Telecorp) - Located a bug in the speedtest.net server list generation and found the correct 'static' url 132 | - Graham Roach (Contact Info?) - Extensive user testing to help determine issues with latency and accuracy of upload and download speeds - #11 (and others) 133 | - @larray - slightly obscure issues with http caches interfering with test results - #20 134 | - Noric - reporting and help with testing issues with report formatting - #32 135 | - @jannson - submitting patch to reduce memory usage on download test - #37 136 | - @vendion - teaching me how to import packages the corret way - #67 137 | - @invalid-email-address - various formatting 138 | - @l2dy - cleaned up README and broken links 139 | - @m01 - speed test mini support 140 | - @pra85 - fixed types in README 141 | - @schweikert - for adding the interface selection code 142 | 143 | Why don't my speeds match those reported from the speedtest.net website? 144 | ======================================================================== 145 | The calculation that is used for testing download speeds is literally measuring the amount of data we are downloading (we request a "random" image and count how many bytes are received) and how long it takes to download. We multiply by the correct factors to get from bytes to megabits. I consider this to be an honest and accurate measurement. 146 | 147 | In speedtest.net's reference documentation they describe doing a lot of manipulation to the results to return an "ideal" measurement (https://support.speedtest.net/entries/20862782-How-does-the-test-itself-work-How-is-the-result-calculated-). This, to me, is trading accuracy for speed and not what I'm looking for out of a testing tool. 148 | 149 | For confirmation that my download calculations are correct I have tested against a few other speed testing sites, specifically http://testmy.net ("What makes TestMy.net better") who appear to use an "unfiltered" method of calculating bandwidth speeds. These results typically match up with speedtest.net cli 150 | 151 | 152 | Reference 153 | ========= 154 | - how does it work - https://support.speedtest.net/entries/20862782-How-does-the-test-itself-work-How-is-the-result-calculated- 155 | - why actual speedtest.net results may be inaccurate - http://testmy.net/ 156 | 157 | -------------------------------------------------------------------------------- /internal/testing_assets/sthttp_test_config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9c1687ea58e5e770-1df5b7cd427370f7-4b62a84526ea1f56 6 | speedtest 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | Rate Your ISP 22 | COPY IP 23 | kilobits 24 | megabits 25 | NEW SERVER 26 | TEST AGAIN 27 | UPLOAD SPEED 28 | DOWNLOAD SPEED 29 | kbps 30 | Mbps 31 | BEGIN TEST 32 | START TEST TO RECOMMENDED SERVER 33 | megabytes 34 | kilobytes 35 | kB/s 36 | MB/s 37 | Mbps 38 | How happy are you with your current Internet service provider? 39 | Very unhappy 40 | Unhappy 41 | Neutral 42 | Happy 43 | Very happy 44 | YOUR RESULT WILL BECOME PART OF A SPEED WAVE 45 | PING 46 | Hosted by 47 | TOTAL TESTS 48 | TO DATE 49 | COPIED 50 | AUTO STARTING SPEED TEST IN 51 | SECONDS 52 | SECOND 53 | ERROR 54 | Try Again 55 | START A SPEED WAVE 56 | Speed Wave Name 57 | Your result is now part of the Speed Wave! 58 | Your Result 59 | Help Us Understand Broadband Costs 60 | Download Package 61 | Upload Package 62 | How much do you pay? 63 | Includes: 64 | Is this your postal code? 65 | SUBMIT 66 | GET A FREE OOKLA SPEEDTEST ACCOUNT 67 | Being logged in would allow you to start a Speed Wave here! 68 | Registration is free and only requires a valid email address. 69 | Your Email Address 70 | https://twitter.com/share?text=Check%20out%20my%20%40Ookla%20Speedtest%20result!%20What%27s%20your%20speed%3F&url=http%3A%2F%2Fwww.speedtest.net%2Fmy-result%2F{RESULTID}&related=ookla%3ACreators%20of%20Ookla%20Speedtest&hashtags=speedtest 71 | https://www.facebook.com/dialog/feed?app_id=581657151866321&link=http://www.speedtest.net/my-result/{RESULTID}&description=This%20is%20my%20Ookla%20Speedtest%20result.%20Compare%20your%20speed%20to%20mine!&redirect_uri=http://www.speedtest.net&name=Check%20out%20my%20Ookla%20Speedtest%20results.%20What%27s%20your%20speed%3F 72 | VIEW SPEED WAVE 73 | CREATE 74 | Speed 75 | Phone 76 | TV 77 | What speeds do you pay for? 78 | Thanks for participating in the survey! 79 | SELECTING BEST SERVER BASED ON PING 80 | MY RESULTS 81 | CREATE 82 | YOUR PREFERRED SERVER 83 | RECOMMENDED SERVER 84 | CONNECTING 85 | COPY 86 | SHARE THIS RESULT 87 | COMPARE 88 | YOUR RESULT 89 | CONTRIBUTE 90 | TO NET INDEX 91 | CLOSE 92 | RETAKE THE 93 | SURVEY 94 | IMAGE 95 | FORUM 96 | Use this test result to begin your own Speed Wave! 97 | Fastest ISPs 98 | wave 99 | share 100 | link:{LANG_CODE}/results.php?source=compare 101 | contribute 102 | bits per second 103 | standard 104 | en 105 | http://pinterest.com/pin/create/button/?url=http%3A%2F%2Fwww.speedtest.net%2F&media=http%3A%2F%2Fspeedtest.net%2Fresult%2F{RESULTID}.png&description=Check%20out%20my%20result%20from%20Ookla%20Speedtest! 106 | 107 | Continue 108 | EDIT 109 | Download 110 | Download: 111 | Upload 112 | Upload: 113 | Connection Type? 114 | Home 115 | Business 116 | School 117 | Public Wi-Fi 118 | Other 119 | My ISP is: 120 | Yes 121 | Wrong 122 | Yes 123 | Wrong 124 | Please enter your postal code 125 | Please enter your ISP name 126 | OK 127 | Please check your upload speed. 128 | This seems faster than expected. 129 | Please check the amount entered. 130 | This seems higher than expected. 131 | Please check your Download speed. 132 | This seems faster than expected. 133 | WEB 134 | EMBED 135 | Are you on 136 | Take our Broadband Internet Survey! 137 | TEST AGAIN 138 | COMPARE 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /cmd/speedtest/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | speedtest is an unofficial commandline interface to speedtest.net 3 | 4 | Version 1.0 was designed as an "app only". Version 2.0 will make a cleaner split between libraries and interface 5 | */ 6 | 7 | package main 8 | 9 | import ( 10 | "context" 11 | "fmt" 12 | "log" 13 | "math/rand" 14 | "net/url" 15 | "os" 16 | "strings" 17 | "time" 18 | 19 | "github.com/zpeters/speedtest/internal/print" 20 | "github.com/zpeters/speedtest/internal/speedtests" 21 | "github.com/zpeters/speedtest/internal/sthttp" 22 | 23 | "github.com/dchest/uniuri" 24 | "github.com/google/go-github/github" 25 | "github.com/spf13/viper" 26 | "github.com/urfave/cli" 27 | ) 28 | 29 | // Version placeholder, injected in Makefile 30 | var Version string 31 | 32 | func runTest(c *cli.Context, stClient *sthttp.Client, tester *speedtests.Tester) { 33 | // create our server object and load initial config 34 | var testServer sthttp.Server 35 | 36 | config, err := stClient.GetConfig() 37 | if err != nil { 38 | log.Printf("Cannot get speedtest config\n") 39 | log.Fatal(err) 40 | } 41 | stClient.Config = &config 42 | 43 | // if we are *not* running a report then say hello to everyone 44 | if !tester.Report { 45 | fmt.Printf("github.com/zpeters/speedtest -- unofficial cli for speedtest.net\n") 46 | } 47 | 48 | // if we are in debug mode print outa an environment report 49 | if stClient.Debug { 50 | print.EnvironmentReport(stClient) 51 | } 52 | 53 | // get all possible servers (excluding blacklisted) 54 | if stClient.Debug { 55 | log.Printf("Getting all servers for our test list") 56 | } 57 | var allServers []sthttp.Server 58 | if c.String("mini") == "" { 59 | allServers, err = stClient.GetServers() 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | } 64 | 65 | // if a mini speedtest installation was specified, use that... 66 | if c.String("mini") != "" { 67 | 68 | //construct testserver object manually 69 | u, err := url.Parse(c.String("mini")) 70 | if err != nil { 71 | log.Fatalf("Speedtest mini server URL is not a valid URL: %s", err) 72 | } 73 | 74 | if stClient.Debug { 75 | log.Printf("Using Mini Server '%s'", c.String("mini")) 76 | } 77 | testServer.URL = c.String("mini") 78 | if !strings.HasSuffix(c.String("mini"), "/") { 79 | testServer.URL += "/" 80 | } 81 | testServer.URL += "speedtest/upload.php" 82 | testServer.Name = u.Host 83 | testServer.Sponsor = "speedtest-mini" 84 | testServer.ID = "0" 85 | 86 | testServer.Latency, err = stClient.GetLatency(testServer, stClient.GetLatencyURL(testServer)) 87 | if err != nil { 88 | log.Fatal(err) 89 | } 90 | 91 | // if they specified a specific speedtest.net server, test against that... 92 | } else if c.String("server") != "" { 93 | if stClient.Debug { 94 | log.Printf("Server '%s' specified, getting info...", c.String("server")) 95 | } 96 | // find server and load latency report 97 | testServer = tester.FindServer(c.String("server"), allServers) 98 | // load latency 99 | testServer.Latency, err = stClient.GetLatency(testServer, stClient.GetLatencyURL(testServer)) 100 | if err != nil { 101 | log.Fatal(err) 102 | } 103 | 104 | if !tester.Report { 105 | fmt.Printf("Server: %s - %s (%s)\n", testServer.ID, testServer.Name, testServer.Sponsor) 106 | } 107 | 108 | // ...otherwise get a list of all servers sorted by distance... 109 | } else { 110 | if stClient.Debug { 111 | log.Printf("Getting closest servers...") 112 | } 113 | closestServers := stClient.GetClosestServers(allServers) 114 | if stClient.Debug { 115 | log.Printf("Getting the fastests of our closest servers...") 116 | } 117 | // ... and get the fastests NUMCLOSEST ones 118 | testServer = stClient.GetFastestServer(closestServers) 119 | if !viper.GetBool("report") { 120 | fmt.Printf("Server: %s - %s (%s)\n", testServer.ID, testServer.Name, testServer.Sponsor) 121 | } 122 | } 123 | 124 | // if ping only then just output latency results and exit nicely... 125 | if c.Bool("ping") { 126 | if c.Bool("report") { 127 | if viper.GetString("algotype") == "max" { 128 | fmt.Printf("%3.2f (Lowest)\n", testServer.Latency) 129 | } else { 130 | fmt.Printf("%3.2f (Avg)\n", testServer.Latency) 131 | } 132 | } else { 133 | if viper.GetString("algotype") == "max" { 134 | fmt.Printf("Ping (Lowest): %3.2f ms\n", testServer.Latency) 135 | } else { 136 | fmt.Printf("Ping (Avg): %3.2f ms\n", testServer.Latency) 137 | } 138 | } 139 | os.Exit(0) 140 | // ...otherwise run our full test 141 | } else { 142 | var dmbps float64 143 | var umbps float64 144 | 145 | if !viper.GetBool("report") { 146 | if c.Bool("downloadonly") { 147 | dmbps = tester.Download(testServer) 148 | } else if c.Bool("uploadonly") { 149 | umbps = tester.Upload(testServer) 150 | } else { 151 | dmbps = tester.Download(testServer) 152 | umbps = tester.Upload(testServer) 153 | } 154 | if viper.GetString("algotype") == "max" { 155 | fmt.Printf("Ping (Lowest): %3.2f ms | Download (Max): %3.2f Mbps | Upload (Max): %3.2f Mbps\n", testServer.Latency, dmbps, umbps) 156 | } else { 157 | fmt.Printf("Ping (Avg): %3.2f ms | Download (Avg): %3.2f Mbps | Upload (Avg): %3.2f Mbps\n", testServer.Latency, dmbps, umbps) 158 | } 159 | 160 | } else { 161 | 162 | fmt.Printf("%s%s%s%s\"%s (%s, %s)\"%s", time.Now().Format("2006-01-02 15:04:05 -0700"), viper.GetString("reportchar"), testServer.ID, viper.GetString("reportchar"), testServer.Sponsor, testServer.Name, testServer.Country, viper.GetString("reportchar")) 163 | fmt.Printf("%3.2f%s", testServer.Latency, viper.GetString("reportchar")) 164 | 165 | if c.Bool("downloadonly") { 166 | dmbps = tester.Download(testServer) 167 | dkbps := dmbps * 1000 168 | fmt.Printf("%d\n", int(dkbps)) 169 | } else if c.Bool("uploadonly") { 170 | umbps = tester.Upload(testServer) 171 | ukbps := umbps * 1000 172 | fmt.Printf("%d\n", int(ukbps)) 173 | } else { 174 | dmbps = tester.Download(testServer) 175 | dkbps := dmbps * 1000 176 | fmt.Printf("%d%s", int(dkbps), viper.GetString("reportchar")) 177 | 178 | umbps = tester.Upload(testServer) 179 | ukbps := umbps * 1000 180 | fmt.Printf("%d\n", int(ukbps)) 181 | } 182 | } 183 | } 184 | } 185 | 186 | func init() { 187 | viper.SetDefault("debug", false) 188 | viper.SetDefault("quiet", false) 189 | viper.SetDefault("report", false) 190 | viper.SetDefault("numclosest", 3) 191 | viper.SetDefault("numlatencytests", 5) 192 | viper.SetDefault("reportchar", "|") 193 | viper.SetDefault("algotype", "max") 194 | viper.SetDefault("httptimeout", 15) 195 | viper.SetDefault("dlsizes", []int{350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000}) 196 | viper.SetDefault("ulsizes", []int{int(0.25 * 1024 * 1024), int(0.5 * 1024 * 1024), int(1.0 * 1024 * 1024), int(1.5 * 1024 * 1024), int(2.0 * 1024 * 1024)}) 197 | viper.SetDefault("speedtestconfigurl", "http://c.speedtest.net/speedtest-config.php?x="+uniuri.New()) 198 | viper.SetDefault("speedtestserversurl", "http://c.speedtest.net/speedtest-servers-static.php?x="+uniuri.New()) 199 | viper.SetDefault("useragent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.21 Safari/537.36") 200 | } 201 | 202 | func main() { 203 | // seeding randomness 204 | rand.Seed(time.Now().UTC().UnixNano()) 205 | 206 | // set logging to stdout for global logger 207 | log.SetOutput(os.Stdout) 208 | 209 | // setting up cli settings 210 | app := cli.NewApp() 211 | app.Name = "speedtest" 212 | app.Usage = "Unofficial command line interface to speedtest.net (https://github.com/zpeters/speedtest)" 213 | app.Author = "Zach Peters - zpeters@gmail.com - github.com/zpeters" 214 | app.Version = Version 215 | 216 | // setup cli flags 217 | app.Flags = []cli.Flag{ 218 | cli.StringFlag{ 219 | Name: "algo, a", 220 | Usage: "Specify the measurement method to use ('max', 'avg')", 221 | }, 222 | cli.BoolFlag{ 223 | Name: "debug, d", 224 | Usage: "Turn on debugging", 225 | }, 226 | cli.BoolFlag{ 227 | Name: "list, l", 228 | Usage: "List available servers", 229 | }, 230 | cli.BoolFlag{ 231 | Name: "update, u", 232 | Usage: "Check for a new version of speedtest", 233 | }, 234 | cli.BoolFlag{ 235 | Name: "ping, p", 236 | Usage: "Ping only mode", 237 | }, 238 | cli.BoolFlag{ 239 | Name: "quiet, q", 240 | Usage: "Quiet mode", 241 | }, 242 | cli.BoolFlag{ 243 | Name: "report, r", 244 | Usage: "Reporting mode output, minimal output with '|' for separators, use '--rc'\n\t\tto change separator characters. Reports the following: Server ID, \n\t\tServer Name (Location), Ping time in ms, Download speed in kbps, Upload speed in kbps", 245 | }, 246 | cli.BoolFlag{ 247 | Name: "downloadonly, do", 248 | Usage: "Only perform download test", 249 | }, 250 | cli.BoolFlag{ 251 | Name: "uploadonly, uo", 252 | Usage: "Only perform upload test", 253 | }, 254 | cli.StringFlag{ 255 | Name: "reportchar, rc", 256 | Usage: "Set the report separator. Example: --rc=','", 257 | }, 258 | cli.StringFlag{ 259 | Name: "server, s", 260 | Usage: "Use a specific server", 261 | }, 262 | cli.StringSliceFlag{ 263 | Name: "blacklist, b", 264 | Usage: "Blacklist a server. Use this multiple times for more than one server", 265 | }, 266 | cli.StringFlag{ 267 | Name: "mini, m", 268 | Usage: "URL of speedtest mini server", 269 | }, 270 | cli.StringFlag{ 271 | Name: "useragent, ua", 272 | Usage: "Specify a useragent string", 273 | }, 274 | cli.IntFlag{ 275 | Name: "numclosest, nc", 276 | Value: viper.GetInt("numclosest"), 277 | Usage: "Number of 'closest' servers to find", 278 | }, 279 | cli.IntFlag{ 280 | Name: "httptimeout, t", 281 | Value: viper.GetInt("httptimeout"), 282 | Usage: "Timeout (seconds) for http connections", 283 | }, 284 | cli.IntFlag{ 285 | Name: "numlatency, nl", 286 | Value: viper.GetInt("numlatencytests"), 287 | Usage: "Number of latency tests to perform", 288 | }, 289 | cli.StringFlag{ 290 | Name: "interface, I", 291 | Usage: "Source IP address or name of an interface", 292 | }, 293 | } 294 | 295 | // toggle our switches and setup variables 296 | app.Action = func(c *cli.Context) { 297 | // just check the version if that is what they want 298 | if c.Bool("update") { 299 | // Check if there is an update 300 | client := github.NewClient(nil) 301 | ctx := context.Background() 302 | latestRelease, _, err := client.Repositories.GetLatestRelease(ctx, "zpeters", "speedtest") 303 | if err != nil { 304 | log.Fatalf("github call: %s", err) 305 | } 306 | githubTag := *latestRelease.TagName 307 | if Version != githubTag { 308 | fmt.Printf("New version %s available at https://github.com/zpeters/speedtest/releases\n", githubTag) 309 | } else { 310 | fmt.Printf("You are up to date\n") 311 | } 312 | os.Exit(0) 313 | } 314 | // set our flags 315 | if c.Bool("debug") { 316 | viper.Set("debug", true) 317 | } 318 | if c.Bool("quiet") { 319 | viper.Set("quiet", true) 320 | } 321 | if c.Bool("report") { 322 | viper.Set("report", true) 323 | } 324 | if c.String("algo") != "" { 325 | if c.String("algo") == "max" { 326 | viper.Set("algotype", "max") 327 | } else if c.String("algo") == "avg" { 328 | viper.Set("algotype", "avg") 329 | } else { 330 | fmt.Printf("** Invalid algorithm '%s'\n", c.String("algo")) 331 | os.Exit(1) 332 | } 333 | } 334 | viper.Set("numclosest", c.Int("numclosest")) 335 | viper.Set("numlatencytests", c.Int("numlatency")) 336 | viper.Set("httptimeout", c.Int("httptimeout")) 337 | if c.String("reportchar") != "" { 338 | viper.Set("reportchar", c.String("reportchar")) 339 | } 340 | if c.String("interface") != "" { 341 | viper.Set("interface", c.String("interface")) 342 | } 343 | if len(c.StringSlice("blacklist")) > 0 { 344 | viper.Set("blacklist", c.StringSlice("blacklist")) 345 | } 346 | 347 | stClient := sthttp.NewClient( 348 | &sthttp.SpeedtestConfig{ 349 | ConfigURL: viper.GetString("speedtestconfigurl"), 350 | ServersURL: viper.GetString("speedtestserversurl"), 351 | AlgoType: viper.GetString("algotype"), 352 | NumClosest: viper.GetInt("numclosest"), 353 | NumLatencyTests: viper.GetInt("numlatencytests"), 354 | Interface: viper.GetString("interface"), 355 | Blacklist: viper.GetStringSlice("blacklist"), 356 | UserAgent: viper.GetString("useragent"), 357 | }, 358 | &sthttp.HTTPConfig{ 359 | HTTPTimeout: viper.GetDuration("httptimeout") * time.Second, 360 | }, 361 | viper.GetBool("debug"), 362 | viper.GetString("reportchar")) 363 | 364 | tester := speedtests.NewTester( 365 | stClient, 366 | viper.Get("dlsizes").([]int), 367 | viper.Get("ulsizes").([]int), 368 | viper.GetBool("quiet"), 369 | viper.GetBool("report")) 370 | 371 | // run a oneshot list 372 | if c.Bool("list") { 373 | tester.ListServers(stClient.SpeedtestConfig.ConfigURL, stClient.SpeedtestConfig.ServersURL, stClient.SpeedtestConfig.Blacklist) 374 | os.Exit(0) 375 | } 376 | 377 | // run our test 378 | runTest(c, stClient, tester) 379 | 380 | // exit nicely 381 | os.Exit(0) 382 | } 383 | 384 | // run the app 385 | app.Run(os.Args) 386 | } 387 | -------------------------------------------------------------------------------- /internal/sthttp/sthttp_test.go: -------------------------------------------------------------------------------- 1 | package sthttp 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | "net/http/httptest" 11 | "os" 12 | "sort" 13 | "testing" 14 | "time" 15 | 16 | "github.com/stretchr/testify/assert" 17 | ) 18 | 19 | func TestCheckHTTPSuccess(t *testing.T) { 20 | resp := http.Response{} 21 | resp.StatusCode = 200 22 | r := checkHTTP(&resp) 23 | if r != true { 24 | t.Fail() 25 | } 26 | } 27 | 28 | func TestCheckHTTPFail(t *testing.T) { 29 | resp := http.Response{} 30 | resp.StatusCode = 404 31 | r := checkHTTP(&resp) 32 | if r != false { 33 | t.Fail() 34 | } 35 | } 36 | 37 | func TestGetLatencyURL(t *testing.T) { 38 | s := Server{} 39 | stc := Client{} 40 | s.URL = "http://example.com/speedtest/" 41 | u := stc.GetLatencyURL(s) 42 | if u != "http://example.com/speedtest/latency.txt" { 43 | t.Logf("Got latency URL: %s\n", u) 44 | t.Fail() 45 | } 46 | } 47 | 48 | func TestServerDistance(t *testing.T) { 49 | s1 := Server{} 50 | s1.Distance = 10 51 | s2 := Server{} 52 | s2.Distance = 20 53 | s3 := Server{} 54 | s3.Distance = 200 55 | s4 := Server{} 56 | s4.Distance = 100 57 | 58 | servers := []Server{s3, s4, s2, s1} 59 | sort.Sort(ByDistance(servers)) 60 | 61 | assert.EqualValues(t, servers[0].Distance, 10, "Servers list not sorted by distance") 62 | assert.EqualValues(t, servers[1].Distance, 20, "Servers list not sorted by distance") 63 | assert.EqualValues(t, servers[2].Distance, 100, "Servers list not sorted by distance") 64 | assert.EqualValues(t, servers[3].Distance, 200, "Servers list not sorted by distance") 65 | } 66 | 67 | func TestServerLatency(t *testing.T) { 68 | s1 := Server{} 69 | s1.Latency = 10 70 | s2 := Server{} 71 | s2.Latency = 20 72 | s3 := Server{} 73 | s3.Latency = 200 74 | s4 := Server{} 75 | s4.Latency = 100 76 | 77 | servers := []Server{s3, s4, s2, s1} 78 | sort.Sort(ByLatency(servers)) 79 | 80 | assert.EqualValues(t, servers[0].Latency, 10, "Servers list not sorted by latency") 81 | assert.EqualValues(t, servers[1].Latency, 20, "Servers list not sorted by latency") 82 | assert.EqualValues(t, servers[2].Latency, 100, "Servers list not sorted by latency") 83 | assert.EqualValues(t, servers[3].Latency, 200, "Servers list not sorted by latency") 84 | } 85 | 86 | func TestGetConfig(t *testing.T) { 87 | x, err := ioutil.ReadFile("../testing_assets/sthttp_test_config.xml") 88 | if err != nil { 89 | t.Logf("Cannot read sthttp_test_config.xml") 90 | } 91 | 92 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 93 | fmt.Fprintln(w, string(x)) 94 | })) 95 | defer ts.Close() 96 | 97 | timeout, _ := time.ParseDuration("15s") 98 | stc := Client{ 99 | SpeedtestConfig: &SpeedtestConfig{ConfigURL: ts.URL}, 100 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 101 | } 102 | c, err := stc.GetConfig() 103 | if err != nil { 104 | t.Logf("Cannot get config") 105 | t.Fatal(err) 106 | } 107 | 108 | assert.EqualValues(t, c.IP, "23.124.0.25", "IP Doesn't match") 109 | assert.EqualValues(t, c.Lat, 32.5155, "Latitude doesn't match") 110 | assert.EqualValues(t, c.Lon, -90.1118, "Longitude doesn't match") 111 | assert.EqualValues(t, c.Isp, "AT&T U-verse", "ISP Doesn't match") 112 | } 113 | 114 | func TestGetConfigNoConnection(t *testing.T) { 115 | timeout, _ := time.ParseDuration("15s") 116 | stc := Client{ 117 | SpeedtestConfig: &SpeedtestConfig{ConfigURL: "fail"}, 118 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 119 | } 120 | _, err := stc.GetConfig() 121 | assert.Error(t, err, "An error was expected") 122 | } 123 | 124 | func TestGetServers(t *testing.T) { 125 | x, err := ioutil.ReadFile("../testing_assets/sthttp_test_servers.xml") 126 | if err != nil { 127 | t.Logf("Cannot read sthttp_test_servers.xml") 128 | } 129 | 130 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 131 | fmt.Fprintln(w, string(x)) 132 | })) 133 | defer ts.Close() 134 | 135 | timeout, _ := time.ParseDuration("15s") 136 | stc := Client{ 137 | SpeedtestConfig: &SpeedtestConfig{ServersURL: ts.URL}, 138 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 139 | } 140 | servers, err := stc.GetServers() 141 | if err != nil { 142 | t.Logf("Cannot get servers") 143 | t.Fatal(err) 144 | } 145 | 146 | //sthttp_test.go:127: Server 0: sthttp.Server{URL:"http://88.84.191.230/speedtest/upload.php", Lat:70.0733, Lon:29.7497, Name:"Vadso", Country:"Norway", CC:"NO", Sponsor:"Varanger KraftUtvikling AS", ID:"4600", Distance:0, Latency:0} 147 | expectURL := "http://88.84.191.230/speedtest/upload.php" 148 | assert.Equal(t, servers[0].URL, expectURL, fmt.Sprintf("Server 0 url should be: '%s'\n", expectURL)) 149 | 150 | expectLat := 59.8833 151 | assert.Equal(t, servers[100].Lat, expectLat, fmt.Sprintf("Server 10 lat should be: '%f'\n", expectLat)) 152 | 153 | expectLon := 15.2 154 | assert.Equal(t, servers[1005].Lon, expectLon, fmt.Sprintf("Server 1050 lat should be: '%f'\n", expectLat)) 155 | 156 | expectName := "Chirchiq" 157 | assert.Equal(t, servers[2021].Name, expectName, fmt.Sprintf("Server 2021 name should be: '%s'\n", expectName)) 158 | 159 | expectCountry := "Lao PDR" 160 | assert.Equal(t, servers[3321].Country, expectCountry, fmt.Sprintf("Server 3321 name should be: '%s'\n", expectCountry)) 161 | 162 | expectCC := "US" 163 | assert.Equal(t, servers[2222].CC, expectCC, fmt.Sprintf("Server 2222 name should be: '%s'\n", expectCC)) 164 | 165 | expectSponsor := "SRT Communications" 166 | assert.Equal(t, servers[1234].Sponsor, expectSponsor, fmt.Sprintf("Server 1234 name should be: '%s'\n", expectSponsor)) 167 | 168 | expectID := "2804" 169 | assert.Equal(t, servers[666].ID, expectID, fmt.Sprintf("Server 666 name should be: '%s'\n", expectID)) 170 | 171 | expectDistance := 0 172 | assert.EqualValues(t, servers[1].Distance, expectDistance, fmt.Sprintf("Server 1 name should be: '%d'\n", expectDistance)) 173 | 174 | expectLatency := 0 175 | assert.EqualValues(t, servers[21].Latency, expectLatency, fmt.Sprintf("Server 21 name should be: '%d'\n", expectLatency)) 176 | 177 | } 178 | 179 | func TestGetServersBlacklist(t *testing.T) { 180 | x, err := ioutil.ReadFile("../testing_assets/sthttp_test_servers.xml") 181 | if err != nil { 182 | t.Logf("Cannot read sthttp_test_servers.xml") 183 | } 184 | 185 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 186 | fmt.Fprintln(w, string(x)) 187 | })) 188 | defer ts.Close() 189 | 190 | timeout, _ := time.ParseDuration("15s") 191 | stc := Client{ 192 | SpeedtestConfig: &SpeedtestConfig{ServersURL: ts.URL, Blacklist: []string{"3484", "4600"}}, 193 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 194 | } 195 | serversBlacklist, err := stc.GetServers() 196 | if err != nil { 197 | t.Logf("Cannot get servers") 198 | t.Fatal(err) 199 | } 200 | stc.SpeedtestConfig.Blacklist = []string{""} 201 | serversAll, err := stc.GetServers() 202 | if err != nil { 203 | t.Logf("Cannot get servers") 204 | t.Fatal(err) 205 | } 206 | 207 | assert.Equal(t, len(serversAll)-2, len(serversBlacklist), "All servers should be one less than blacklist list") 208 | 209 | } 210 | 211 | func TestGetClosestServers(t *testing.T) { 212 | x, err := ioutil.ReadFile("../testing_assets/sthttp_test_servers.xml") 213 | if err != nil { 214 | t.Logf("Cannot read sthttp_test_servers.xml") 215 | } 216 | 217 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 218 | fmt.Fprintln(w, string(x)) 219 | })) 220 | defer ts.Close() 221 | 222 | timeout, _ := time.ParseDuration("15s") 223 | stc := Client{ 224 | SpeedtestConfig: &SpeedtestConfig{ServersURL: ts.URL}, Config: &Config{}, 225 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 226 | } 227 | servers, err := stc.GetServers() 228 | if err != nil { 229 | t.Logf("Cannot get servers") 230 | t.Fatal(err) 231 | } 232 | 233 | lat := 32.5155 234 | lon := -90.1118 235 | stc.Config.Lat = lat 236 | stc.Config.Lon = lon 237 | sorted := stc.GetClosestServers(servers) 238 | 239 | assert.Equal(t, sorted[0].ID, "2630", "Closest server ID should be 2630") 240 | } 241 | 242 | func TestGetLatency(t *testing.T) { 243 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 244 | time.Sleep(100 * time.Millisecond) 245 | fmt.Fprintln(w, "Hello World") 246 | })) 247 | defer ts.Close() 248 | 249 | s := Server{} 250 | 251 | timeout, _ := time.ParseDuration("15s") 252 | stc := Client{ 253 | SpeedtestConfig: &SpeedtestConfig{NumLatencyTests: 5}, 254 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 255 | } 256 | latency, err := stc.GetLatency(s, ts.URL) 257 | assert.NoError(t, err, "Error getting latency") 258 | assert.True(t, latency > 100, "Latency faster than expected") 259 | } 260 | 261 | func TestGetFastestServer(t *testing.T) { 262 | x, err := ioutil.ReadFile("../testing_assets/sthttp_test_servers.xml") 263 | if err != nil { 264 | t.Logf("Cannot read sthttp_test_servers.xml") 265 | } 266 | 267 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 268 | fmt.Fprintln(w, string(x)) 269 | })) 270 | defer ts.Close() 271 | 272 | timeout, _ := time.ParseDuration("15s") 273 | stc := Client{ 274 | SpeedtestConfig: &SpeedtestConfig{ServersURL: ts.URL}, 275 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 276 | } 277 | servers, err := stc.GetServers() 278 | if err != nil { 279 | t.Logf("Cannot get servers") 280 | t.Fatal(err) 281 | } 282 | 283 | fs := stc.GetFastestServer(servers) 284 | assert.NotNil(t, fs, "No fastest server returned") 285 | } 286 | 287 | func TestFastestServerWithTimeout(t *testing.T) { 288 | // Setup test server to check for latency 289 | testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 290 | if r.URL.Path == "/slow/latency.txt" { 291 | sleepDuration, _ := time.ParseDuration("0.2s") 292 | time.Sleep(sleepDuration) 293 | } 294 | w.WriteHeader(http.StatusOK) 295 | io.WriteString(w, "Hello") 296 | })) 297 | defer testServer.Close() 298 | 299 | // Setup server to list 2 server one that will timeout, one that wont 300 | slowServerXML := "\n" 301 | fastServerXML := "\n" 302 | 303 | listServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 304 | w.WriteHeader(http.StatusOK) 305 | serverList := "\n\n" + slowServerXML + fastServerXML + "\n\n" 306 | io.WriteString(w, serverList) 307 | })) 308 | defer listServer.Close() 309 | 310 | // Setup client with short timeout 311 | timeout, _ := time.ParseDuration("0.1s") 312 | stc := Client{ 313 | SpeedtestConfig: &SpeedtestConfig{ServersURL: listServer.URL, NumLatencyTests: 1}, 314 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 315 | Debug: true, 316 | } 317 | servers, err := stc.GetServers() 318 | if err != nil { 319 | t.Logf("Cannot get servers") 320 | t.Fatal(err) 321 | } 322 | 323 | var buf bytes.Buffer 324 | log.SetOutput(&buf) 325 | fs := stc.GetFastestServer(servers) 326 | log.SetOutput(os.Stdout) 327 | // Make sure timeout was logged 328 | assert.True(t, bytes.Contains(buf.Bytes(), []byte("Server 0 timed out")), "Timeout must be logged") 329 | // Make sure correct server returned 330 | assert.NotNil(t, fs, "No fastest server returned") 331 | assert.Equal(t, fs.Name, "fast", "Fast server should be returned") 332 | } 333 | 334 | func TestDownloadSpeed(t *testing.T) { 335 | f, err := os.Open("../testing_assets/random750x750.jpg") 336 | assert.NoError(t, err, "Can't open test file") 337 | defer f.Close() 338 | 339 | b, err := ioutil.ReadAll(f) 340 | assert.NoError(t, err, "Can't read test file") 341 | 342 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 343 | fmt.Fprintln(w, b) 344 | })) 345 | defer ts.Close() 346 | 347 | timeout, _ := time.ParseDuration("15s") 348 | stc := Client{ 349 | SpeedtestConfig: &SpeedtestConfig{}, 350 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 351 | } 352 | res, err := stc.DownloadSpeed(ts.URL) 353 | assert.NoError(t, err, "There should be no error") 354 | assert.True(t, res > 0, "Download speed should be faster than zero") 355 | } 356 | 357 | func TestDownloadSpeedBadUrl(t *testing.T) { 358 | timeout, _ := time.ParseDuration("15s") 359 | stc := Client{ 360 | SpeedtestConfig: &SpeedtestConfig{}, 361 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 362 | } 363 | res, err := stc.DownloadSpeed("http://0.0.0.0") 364 | assert.Error(t, err, "This should fail") 365 | assert.EqualValues(t, res, 0, "Failed download, so speed should be 0") 366 | } 367 | 368 | func TestUploadSpeed(t *testing.T) { 369 | f, err := os.Open("../testing_assets/random750x750.jpg") 370 | assert.NoError(t, err, "Can't open test file") 371 | defer f.Close() 372 | 373 | b, err := ioutil.ReadAll(f) 374 | assert.NoError(t, err, "Can't read test file") 375 | 376 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 377 | fmt.Fprintln(w, b) 378 | })) 379 | defer ts.Close() 380 | 381 | timeout, _ := time.ParseDuration("15s") 382 | stc := Client{ 383 | SpeedtestConfig: &SpeedtestConfig{}, 384 | HTTPConfig: &HTTPConfig{HTTPTimeout: timeout}, 385 | } 386 | res, err := stc.UploadSpeed(ts.URL, "text/xml", b) 387 | assert.True(t, res > 0, "Upload speed should be greater than 0") 388 | assert.NoError(t, err, "Upload should not error out") 389 | } 390 | -------------------------------------------------------------------------------- /internal/sthttp/sthttp.go: -------------------------------------------------------------------------------- 1 | package sthttp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/xml" 6 | "errors" 7 | "io/ioutil" 8 | "log" 9 | "net" 10 | "net/http" 11 | "net/url" 12 | "sort" 13 | "strings" 14 | "time" 15 | 16 | "github.com/zpeters/speedtest/internal/coords" 17 | "github.com/zpeters/speedtest/internal/misc" 18 | ) 19 | 20 | // TheClient is our users information 21 | type TheClient struct { 22 | IP string `xml:"ip,attr"` 23 | Lat string `xml:"lat,attr"` 24 | Lon string `xml:"lon,attr"` 25 | Isp string `xml:"isp,attr"` 26 | } 27 | 28 | // XMLConfigSettings is a container for settings 29 | type XMLConfigSettings struct { 30 | XMLName xml.Name `xml:"settings"` 31 | Client TheClient `xml:"client"` 32 | } 33 | 34 | // XMLServer is a candidate server 35 | type XMLServer struct { 36 | XMLName xml.Name `xml:"server"` 37 | URL string `xml:"url,attr"` 38 | Lat string `xml:"lat,attr"` 39 | Lon string `xml:"lon,attr"` 40 | Name string `xml:"name,attr"` 41 | Country string `xml:"country,attr"` 42 | CC string `xml:"cc,attr"` 43 | Sponsor string `xml:"sponsor,attr"` 44 | ID string `xml:"id,attr"` 45 | } 46 | 47 | // TheServersContainer is a list of servers 48 | type TheServersContainer struct { 49 | XMLName xml.Name `xml:"servers"` 50 | XMLServers []XMLServer `xml:"server"` 51 | } 52 | 53 | // ServerSettings is the servers part of the setings 54 | type ServerSettings struct { 55 | XMLName xml.Name `xml:"settings"` 56 | ServersContainer TheServersContainer `xml:"servers"` 57 | } 58 | 59 | // Config struct holds our config (users current ip, lat, lon and isp) 60 | type Config struct { 61 | IP string 62 | Lat float64 63 | Lon float64 64 | Isp string 65 | } 66 | 67 | // Client define a Speedtest HTTP client 68 | type Client struct { 69 | Config *Config 70 | SpeedtestConfig *SpeedtestConfig 71 | HTTPConfig *HTTPConfig 72 | Debug bool 73 | ReportChar string 74 | } 75 | 76 | // SpeedtestConfig define Speedtest settings 77 | type SpeedtestConfig struct { 78 | ConfigURL string 79 | ServersURL string 80 | AlgoType string 81 | NumClosest int 82 | NumLatencyTests int 83 | Interface string 84 | Blacklist []string 85 | UserAgent string 86 | } 87 | 88 | // HTTPConfig define settings for HTTP requests 89 | type HTTPConfig struct { 90 | HTTPTimeout time.Duration 91 | } 92 | 93 | // NewClient define a new Speedtest client. 94 | func NewClient(speedtestConfig *SpeedtestConfig, httpConfig *HTTPConfig, debug bool, reportChar string) *Client { 95 | return &Client{ 96 | Config: &Config{}, 97 | HTTPConfig: httpConfig, 98 | SpeedtestConfig: speedtestConfig, 99 | Debug: debug, 100 | ReportChar: reportChar, 101 | } 102 | 103 | } 104 | 105 | // Server struct is a speedtest candidate server 106 | type Server struct { 107 | URL string 108 | Lat float64 109 | Lon float64 110 | Name string 111 | Country string 112 | CC string 113 | Sponsor string 114 | ID string 115 | Distance float64 116 | Latency float64 117 | } 118 | 119 | // ByDistance allows us to sort servers by distance 120 | type ByDistance []Server 121 | 122 | func (server ByDistance) Len() int { 123 | return len(server) 124 | } 125 | 126 | func (server ByDistance) Less(i, j int) bool { 127 | return server[i].Distance < server[j].Distance 128 | } 129 | 130 | func (server ByDistance) Swap(i, j int) { 131 | server[i], server[j] = server[j], server[i] 132 | } 133 | 134 | // ByLatency allows us to sort servers by latency 135 | type ByLatency []Server 136 | 137 | func (server ByLatency) Len() int { 138 | return len(server) 139 | } 140 | 141 | func (server ByLatency) Less(i, j int) bool { 142 | return server[i].Latency < server[j].Latency 143 | } 144 | 145 | func (server ByLatency) Swap(i, j int) { 146 | server[i], server[j] = server[j], server[i] 147 | } 148 | 149 | // checkBlacklisted tests if the server is on the specified blacklist 150 | func checkBlacklisted(blacklist []string, server string) bool { 151 | var isBlacklisted = false 152 | for b := range blacklist { 153 | if server == blacklist[b] { 154 | isBlacklisted = true 155 | } 156 | } 157 | return isBlacklisted 158 | } 159 | 160 | // checkHTTP tests if http response is successful (200) or not 161 | func checkHTTP(resp *http.Response) bool { 162 | var ok bool 163 | if resp.StatusCode != 200 { 164 | ok = false 165 | } else { 166 | ok = true 167 | } 168 | return ok 169 | } 170 | 171 | // GetConfig downloads the master config from speedtest.net 172 | func (stClient *Client) GetConfig() (c Config, err error) { 173 | c = Config{} 174 | 175 | client := &http.Client{ 176 | Timeout: stClient.HTTPConfig.HTTPTimeout, 177 | } 178 | 179 | req, err := http.NewRequest("GET", stClient.SpeedtestConfig.ConfigURL, nil) 180 | if err != nil { 181 | return c, err 182 | } 183 | req.Header.Set("Cache-Control", "no-cache") 184 | req.Header.Set("User-Agent", stClient.SpeedtestConfig.UserAgent) 185 | 186 | resp, err := client.Do(req) 187 | if err != nil { 188 | return c, err 189 | } 190 | defer resp.Body.Close() 191 | if checkHTTP(resp) != true { 192 | log.Fatalf("Couldn't retrieve our config from speedtest.net: '%s'\n", resp.Status) 193 | } 194 | 195 | body, err := ioutil.ReadAll(resp.Body) 196 | 197 | cx := new(XMLConfigSettings) 198 | 199 | err = xml.Unmarshal(body, &cx) 200 | 201 | c.IP = cx.Client.IP 202 | c.Lat = misc.ToFloat(cx.Client.Lat) 203 | c.Lon = misc.ToFloat(cx.Client.Lon) 204 | c.Isp = cx.Client.Isp 205 | 206 | return c, err 207 | } 208 | 209 | // GetServers will get the full server list 210 | func (stClient *Client) GetServers() (servers []Server, err error) { 211 | client := &http.Client{ 212 | Timeout: stClient.HTTPConfig.HTTPTimeout, 213 | } 214 | req, _ := http.NewRequest("GET", stClient.SpeedtestConfig.ServersURL, nil) 215 | req.Header.Set("Cache-Control", "no-cache") 216 | req.Header.Set("User-Agent", stClient.SpeedtestConfig.UserAgent) 217 | 218 | resp, err := client.Do(req) 219 | 220 | if err != nil { 221 | return servers, err 222 | } 223 | defer resp.Body.Close() 224 | 225 | body, err2 := ioutil.ReadAll(resp.Body) 226 | if err2 != nil { 227 | return servers, err2 228 | } 229 | 230 | s := new(ServerSettings) 231 | 232 | err3 := xml.Unmarshal(body, &s) 233 | if err3 != nil { 234 | return servers, err3 235 | } 236 | 237 | for xmlServer := range s.ServersContainer.XMLServers { 238 | // check if server is blacklisted 239 | if checkBlacklisted(stClient.SpeedtestConfig.Blacklist, s.ServersContainer.XMLServers[xmlServer].ID) == false { 240 | server := new(Server) 241 | server.URL = s.ServersContainer.XMLServers[xmlServer].URL 242 | server.Lat = misc.ToFloat(s.ServersContainer.XMLServers[xmlServer].Lat) 243 | server.Lon = misc.ToFloat(s.ServersContainer.XMLServers[xmlServer].Lon) 244 | server.Name = s.ServersContainer.XMLServers[xmlServer].Name 245 | server.Country = s.ServersContainer.XMLServers[xmlServer].Country 246 | server.CC = s.ServersContainer.XMLServers[xmlServer].CC 247 | server.Sponsor = s.ServersContainer.XMLServers[xmlServer].Sponsor 248 | server.ID = s.ServersContainer.XMLServers[xmlServer].ID 249 | servers = append(servers, *server) 250 | } 251 | } 252 | return servers, nil 253 | } 254 | 255 | // GetClosestServers takes the full server list and sorts by distance 256 | func (stClient *Client) GetClosestServers(servers []Server) []Server { 257 | if stClient.Debug { 258 | log.Printf("Sorting all servers by distance...\n") 259 | } 260 | 261 | myCoords := coords.Coordinate{ 262 | Lat: stClient.Config.Lat, 263 | Lon: stClient.Config.Lon, 264 | } 265 | for server := range servers { 266 | theirlat := servers[server].Lat 267 | theirlon := servers[server].Lon 268 | theirCoords := coords.Coordinate{Lat: theirlat, Lon: theirlon} 269 | 270 | servers[server].Distance = coords.HsDist(coords.DegPos(myCoords.Lat, myCoords.Lon), coords.DegPos(theirCoords.Lat, theirCoords.Lon)) 271 | } 272 | 273 | sort.Sort(ByDistance(servers)) 274 | 275 | return servers 276 | } 277 | 278 | // GetLatencyURL will return the proper url for the latency 279 | func (stClient *Client) GetLatencyURL(server Server) string { 280 | u := server.URL 281 | splits := strings.Split(u, "/") 282 | baseURL := strings.Join(splits[1:len(splits)-1], "/") 283 | latencyURL := "http:/" + baseURL + "/latency.txt" 284 | return latencyURL 285 | } 286 | 287 | // GetLatency will test the latency (ping) the given server NUMLATENCYTESTS times and return either the lowest or average depending on what algorithm is set 288 | func (stClient *Client) GetLatency(server Server, url string) (result float64, err error) { 289 | var latency time.Duration 290 | var minLatency time.Duration 291 | var avgLatency time.Duration 292 | 293 | for i := 0; i < stClient.SpeedtestConfig.NumLatencyTests; i++ { 294 | var failed bool 295 | var finish time.Time 296 | 297 | if stClient.Debug { 298 | log.Printf("Testing latency: %s (%s)\n", server.Name, server.Sponsor) 299 | } 300 | 301 | start := time.Now() 302 | 303 | client, err := stClient.getHTTPClient() 304 | if err != nil { 305 | return result, err 306 | } 307 | req, _ := http.NewRequest("GET", url, nil) 308 | req.Header.Set("Cache-Control", "no-cache") 309 | req.Header.Set("User-Agent", stClient.SpeedtestConfig.UserAgent) 310 | 311 | resp, err := client.Do(req) 312 | 313 | if err != nil { 314 | return result, err 315 | } 316 | 317 | defer resp.Body.Close() 318 | finish = time.Now() 319 | _, err2 := ioutil.ReadAll(resp.Body) 320 | if err2 != nil { 321 | return result, err 322 | } 323 | 324 | if failed == true { 325 | latency = 1 * time.Minute 326 | } else { 327 | latency = finish.Sub(start) 328 | } 329 | 330 | if stClient.Debug { 331 | log.Printf("\tRun took: %v\n", latency) 332 | } 333 | 334 | if stClient.SpeedtestConfig.AlgoType == "max" { 335 | if minLatency == 0 { 336 | minLatency = latency 337 | } else if latency < minLatency { 338 | minLatency = latency 339 | } 340 | } else { 341 | avgLatency = avgLatency + latency 342 | } 343 | 344 | } 345 | 346 | if stClient.SpeedtestConfig.AlgoType == "max" { 347 | result = float64(time.Duration(minLatency.Nanoseconds())*time.Nanosecond) / 1000000 348 | } else { 349 | result = float64(time.Duration(avgLatency.Nanoseconds())*time.Nanosecond) / 1000000 / float64(stClient.SpeedtestConfig.NumLatencyTests) 350 | } 351 | 352 | return result, nil 353 | 354 | } 355 | 356 | // GetFastestServer test all servers until we find numServers that 357 | // respond, then find the fastest of them. Some servers show up in the 358 | // master list but timeout or are "corrupt" therefore we bump their 359 | // latency to something really high (1 minute) and they will drop out of 360 | // this test 361 | func (stClient *Client) GetFastestServer(servers []Server) Server { 362 | var successfulServers []Server 363 | 364 | for server := range servers { 365 | if stClient.Debug { 366 | log.Printf("Doing %d runs of %v\n", stClient.SpeedtestConfig.NumClosest, servers[server]) 367 | } 368 | latency, err := stClient.GetLatency(servers[server], stClient.GetLatencyURL(servers[server])) 369 | if err != nil { 370 | urlerr, ok := err.(*url.Error) 371 | // If error is a url error and has timed out 372 | if ok && urlerr.Timeout() { 373 | if stClient.Debug { 374 | log.Printf("Server %d timed out, skipping...\n", server) 375 | } 376 | continue 377 | } else { 378 | log.Fatal(err) 379 | } 380 | } 381 | 382 | if stClient.Debug { 383 | log.Printf("Total runs took: %v\n", latency) 384 | } 385 | 386 | if latency > float64(time.Duration(1*time.Minute)) { 387 | if stClient.Debug { 388 | log.Printf("Server %d was too slow, skipping...\n", server) 389 | } 390 | } else { 391 | if stClient.Debug { 392 | log.Printf("Server latency was ok %f adding to successful servers list", latency) 393 | } 394 | newServer := servers[server] 395 | newServer.Latency = latency 396 | successfulServers = append(successfulServers, newServer) 397 | } 398 | 399 | if len(successfulServers) == stClient.SpeedtestConfig.NumClosest { 400 | break 401 | } 402 | } 403 | 404 | if len(successfulServers) <= 0 { 405 | log.Fatal("No servers responded") 406 | } 407 | 408 | sort.Sort(ByLatency(successfulServers)) 409 | if stClient.Debug { 410 | log.Printf("Server: %v is the fastest server\n", successfulServers[0]) 411 | } 412 | return successfulServers[0] 413 | } 414 | 415 | // DownloadSpeed measures the mbps of downloading a URL 416 | func (stClient *Client) DownloadSpeed(url string) (speed float64, err error) { 417 | start := time.Now() 418 | if stClient.Debug { 419 | log.Printf("Starting test at: %s\n", start) 420 | } 421 | client, err := stClient.getHTTPClient() 422 | if err != nil { 423 | return 0, err 424 | } 425 | req, err := http.NewRequest("GET", url, nil) 426 | if err != nil { 427 | return 0, err 428 | } 429 | req.Header.Set("Cache-Control", "no-cache") 430 | req.Header.Set("User-Agent", stClient.SpeedtestConfig.UserAgent) 431 | 432 | resp, err := client.Do(req) 433 | if err != nil { 434 | return 0, err 435 | } 436 | defer resp.Body.Close() 437 | 438 | body, err := ioutil.ReadAll(resp.Body) 439 | if err != nil { 440 | log.Fatal(err) 441 | } 442 | bodyLen := len(body) 443 | finish := time.Now() 444 | 445 | bits := float64(bodyLen * 8) 446 | megabits := bits / float64(1000) / float64(1000) 447 | seconds := finish.Sub(start).Seconds() 448 | mbps := megabits / float64(seconds) 449 | 450 | return mbps, err 451 | } 452 | 453 | // UploadSpeed measures the mbps to http.Post to a URL 454 | func (stClient *Client) UploadSpeed(url string, mimetype string, data []byte) (speed float64, err error) { 455 | buf := bytes.NewBuffer(data) 456 | 457 | start := time.Now() 458 | if stClient.Debug { 459 | log.Printf("Starting test at: %s\n", start) 460 | log.Printf("Starting test at: %d (nano)\n", start.UnixNano()) 461 | } 462 | 463 | client, err := stClient.getHTTPClient() 464 | if err != nil { 465 | return 0, err 466 | } 467 | resp, err := client.Post(url, mimetype, buf) 468 | finish := time.Now() 469 | if err != nil { 470 | return 0, err 471 | } 472 | 473 | defer resp.Body.Close() 474 | _, err = ioutil.ReadAll(resp.Body) 475 | if err != nil { 476 | return 0, err 477 | } 478 | 479 | if stClient.Debug { 480 | log.Printf("Finishing test at: %s\n", finish) 481 | log.Printf("Finishing test at: %d (nano)\n", finish.UnixNano()) 482 | log.Printf("Took: %d (nano)\n", finish.Sub(start).Nanoseconds()) 483 | } 484 | 485 | bits := float64(len(data) * 8) 486 | megabits := bits / float64(1000) / float64(1000) 487 | seconds := finish.Sub(start).Seconds() 488 | 489 | mbps := megabits / float64(seconds) 490 | return mbps, nil 491 | } 492 | 493 | func (stClient *Client) getSourceIP() (string, error) { 494 | interfaceOption := stClient.SpeedtestConfig.Interface 495 | if interfaceOption == "" { 496 | return "", nil 497 | } 498 | 499 | // does it look like an IP address? 500 | if net.ParseIP(interfaceOption) != nil { 501 | return interfaceOption, nil 502 | } 503 | 504 | // assume that it is the name of an interface 505 | iface, err := net.InterfaceByName(interfaceOption) 506 | if err != nil { 507 | return "", err 508 | } 509 | 510 | addrs, err := iface.Addrs() 511 | if err != nil { 512 | return "", err 513 | } 514 | 515 | for _, addr := range addrs { 516 | switch v := addr.(type) { 517 | case *net.IPNet: 518 | // fixme: IPv6 support is missing 519 | if v.IP.To4() != nil { 520 | return v.IP.String(), nil 521 | } 522 | case *net.IPAddr: 523 | if v.IP.To4() != nil { 524 | return v.IP.String(), nil 525 | } 526 | } 527 | } 528 | 529 | return "", errors.New("no address found") 530 | } 531 | 532 | func (stClient *Client) getHTTPClient() (*http.Client, error) { 533 | var dialer net.Dialer 534 | 535 | sourceIP, err := stClient.getSourceIP() 536 | if err != nil { 537 | return nil, err 538 | } 539 | if sourceIP != "" { 540 | bindAddrIP, err := net.ResolveIPAddr("ip", sourceIP) 541 | if err != nil { 542 | return nil, err 543 | } 544 | bindAddr := net.TCPAddr{ 545 | IP: bindAddrIP.IP, 546 | } 547 | dialer = net.Dialer{ 548 | LocalAddr: &bindAddr, 549 | Timeout: stClient.HTTPConfig.HTTPTimeout, 550 | KeepAlive: stClient.HTTPConfig.HTTPTimeout, 551 | } 552 | } else { 553 | dialer = net.Dialer{ 554 | Timeout: stClient.HTTPConfig.HTTPTimeout, 555 | KeepAlive: stClient.HTTPConfig.HTTPTimeout, 556 | } 557 | } 558 | transport := &http.Transport{ 559 | Proxy: http.ProxyFromEnvironment, 560 | Dial: dialer.Dial, 561 | TLSHandshakeTimeout: stClient.HTTPConfig.HTTPTimeout, 562 | } 563 | client := &http.Client{ 564 | Timeout: stClient.HTTPConfig.HTTPTimeout, 565 | Transport: transport, 566 | } 567 | return client, nil 568 | } 569 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------