187 | Source code
188 |
191 |
192 |
193 |
--------------------------------------------------------------------------------
/systemd/speedtest.service:
--------------------------------------------------------------------------------
1 | # Systemd unit file for speedtest-go. The defaults below are suitable for
2 | # running all configurations in a medium-security environment. See comments
3 | # below for addtional caveats - particularly those labelled "IMPORTANT".
4 |
5 | # You can edit this file, or alternatively you may prefer to use systemd's
6 | # "override" mechanisms, to avoid editing this file e.g. using:
7 |
8 | # systemctl edit speedtest.service
9 |
10 | [Unit]
11 | Description=Speedtest-go Server
12 | After=syslog.target network.target
13 |
14 | # Default to using socket activation (see accompanying socket unit file to
15 | # configure the bind address etc.).
16 | Requires=speedtest.socket
17 | After=speedtest.socket
18 |
19 | [Service]
20 | Type=simple
21 | # The paths to the installed binary and configuration file:
22 |
23 | ExecStart=/usr/local/bin/speedtest -c /usr/local/etc/speedtest-settings.toml
24 | #WorkingDirectory=/usr/local/share/speedtest
25 | #Restart=always
26 | #RestartSec=5
27 |
28 | # IMPORTANT!
29 | # If you use a database file (not server), then you will need to disable the
30 | # DynamicUser setting, and manually create the UNIX user and group specified
31 | # below, to ensure the file is accessible across multiple invocations of the
32 | # service.
33 | DynamicUser=true
34 |
35 | # You may prefer to use a different user or group name on your system.
36 | User=speedtest
37 | Group=speedtest
38 |
39 |
40 | # The following options will work for all configurations, but are not the
41 | # most secure, so you are advised to customise them as described below:
42 |
43 | # If NOT using socket activation, or if using socket activation AND
44 | # connecting to an external database server (MySQL, postgres) via TCP:
45 | RestrictAddressFamilies=AF_INET AF_INET6
46 |
47 | # If connecting to an external database via unix domain sockets (MySQL
48 | # default to this mode of operation):
49 | RestrictAddressFamilies=AF_UNIX
50 |
51 | # If using 'none', 'memory', or 'bolt' database types, and socket activation
52 | # then the process will not need to bind to any new sockets, so we can remove
53 | # the earlier AF_UNIX option again. In systemd versions before 249 this is
54 | # the only way to say "Restrict the use of all address families":
55 | RestrictAddressFamilies=AF_UNIX
56 | RestrictAddressFamilies=~AF_UNIX
57 | # ...in systemd version 249 and later, we can instead use the much clearer:
58 | #RestrictAddressFamilies=none
59 |
60 | # The following options are available (in systemd v247) to restrict the
61 | # actions of the speedtest server for reasons of increased security.
62 |
63 | # As a whole, the purpose of these are to provide an additional layer of
64 | # security by mitigating any unknown security vulnerabilities which may exist
65 | # in speedtest or in the libraries, tools and operating system components
66 | # which it relies upon.
67 |
68 | # IMPORTANT!
69 | # The following line must be customised to your individual requirements.
70 | # e.g. if using the 'bolt' in-process database type:
71 | ReadWritePaths=/usr/local/var/speedtest
72 |
73 | # Makes created files group-readable, but inaccessible by others
74 | UMask=027
75 |
76 | # Many of the following options are desribed in the systemd.resource-control(5)
77 | # manual page.
78 |
79 | # The following may be useful in your environment:
80 | #IPAddressDeny=
81 | #IPAddressAllow=
82 | #IPAccounting=true
83 | #IPIngressFilterPath=
84 | #SocketBindAllow=
85 |
86 | # If your system doesn't support all of the features below (e.g. because of
87 | # the use of a version of systemd older than 247), you may need to comment-out
88 | # some of the following lines.
89 |
90 | # n.b. It may be possible to further restrict speedtest, but this is a good
91 | # start, and will guard against many potential zero-day vulnerabilities.
92 |
93 | # See the output of `systemd-analyze security speedtest.service` for further
94 | # opportunities. Patches welcome!
95 |
96 | CapabilityBoundingSet=
97 | LockPersonality=true
98 | MemoryDenyWriteExecute=true
99 | NoNewPrivileges=yes
100 | PrivateTmp=yes
101 | PrivateDevices=true
102 | PrivateUsers=true
103 | ProtectSystem=strict
104 | ProtectHome=yes
105 | ProtectClock=true
106 | ProtectControlGroups=true
107 | ProtectKernelLogs=true
108 | ProtectKernelModules=true
109 | ProtectKernelTunables=true
110 | ProtectProc=invisible
111 | ProtectHostname=true
112 | RemoveIPC=true
113 | RestrictNamespaces=true
114 | RestrictSUIDSGID=true
115 | RestrictRealtime=true
116 | SystemCallArchitectures=native
117 | SystemCallFilter=@system-service
118 |
119 | # Additionally, you may wish to use some of the systemd options documented in
120 | # systemd.resource-control(5) to limit the CPU, memory, file-system I/O and
121 | # network I/O that the speedtest server is permitted to consume according to
122 | # the individual requirements of your installation.
123 |
124 | #CPUQuota=25%
125 | #MemoryMax=bytes
126 | #MemorySwapMax=bytes
127 | #TasksMax=N
128 | #IOReadBandwidthMax=device bytes
129 | #IOWriteBandwidthMax=device bytes
130 | #IOReadIOPSMax=device IOPS, IOWriteIOPSMax=device IOPS
131 | #IPAccounting=true
132 | #IPAddressAllow=
133 |
134 | [Install]
135 | WantedBy=multi-user.target
136 |
--------------------------------------------------------------------------------
/web/assets/example-singleServer-progressBar.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | LibreSpeed Example
7 |
8 |
9 |
51 |
52 |
173 |
174 |
175 |
163 | {{ if .NoPassword }}
164 | Please set statistics_password in settings.toml to enable access.
165 | {{ else if .LoggedIn }}
166 |
167 |
174 |
175 | {{ range $i, $v := .Data }}
176 |
177 |
Test ID
{{ $v.UUID }}
178 |
Date and time
{{ $v.Timestamp }}
179 |
IP and ISP Info
{{ $v.IPAddress }} {{ $v.ISPInfo }}
180 |
User agent and locale
{{ $v.UserAgent }} {{ $v.Language }}
181 |
Download speed
{{ $v.Download }}
182 |
Upload speed
{{ $v.Upload }}
183 |
Ping
{{ $v.Ping }}
184 |
Jitter
{{ $v.Jitter }}
185 |
Log
{{ $v.Log }}
186 |
Extra info
{{ $v.Extra }}
187 |
188 | {{ end }}
189 | {{ else }}
190 |
195 | {{ end }}
196 |
197 | `
198 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # LibreSpeed
4 |
5 | No Flash, No Java, No WebSocket, No Bullshit.
6 |
7 | This is a very lightweight speed test implemented in JavaScript, using XMLHttpRequest and Web Workers.
8 |
9 | ## Try it
10 | [Take a speed test](https://speedtest.zzz.cat)
11 |
12 | ## Compatibility
13 | All modern browsers are supported: IE11, latest Edge, latest Chrome, latest Firefox, latest Safari.
14 | Works with mobile versions too.
15 |
16 | ## Features
17 | * Download
18 | * Upload
19 | * Ping
20 | * Jitter
21 | * IP Address, ISP, distance from server (optional)
22 | * Telemetry (optional)
23 | * Results sharing (optional)
24 | * Multiple Points of Test (optional)
25 | * Compatible with PHP frontend predefined endpoints (with `.php` suffixes)
26 | * Supports [Proxy Protocol](https://www.haproxy.org/download/2.3/doc/proxy-protocol.txt) (without TLV support yet)
27 |
28 | 
29 |
30 | ## Server requirements
31 | * Any [Go supported platforms](https://github.com/golang/go/wiki/MinimumRequirements)
32 | * BoltDB, PostgreSQL or MySQL database to store test results (optional)
33 | * A fast! Internet connection
34 |
35 | ## Installation
36 |
37 | ### Install using prebuilt binaries
38 |
39 | 1. Download the appropriate binary file from the [releases](https://github.com/librespeed/speedtest-go/releases/) page.
40 | 2. Unzip the archive.
41 | 3. Make changes to the configuration.
42 | 4. Run the binary.
43 | 5. Optional: Setup a systemd service file.
44 |
45 | ### Use Ansible for automatic installation
46 |
47 | You can use an Ansible role for installing speedtest-go easily. You can find the role on the [Ansible galaxy](https://galaxy.ansible.com/flymia/ansible_speedtest_go). There is a [separate repository](https://github.com/flymia/ansible-speedtest_go) for documentation about the Ansible role.
48 | ### Compile from source
49 |
50 | You need Go 1.16+ to compile the binary. If you have an older version of Go and don't want to install the tarball
51 | manually, you can install newer version of Go into your `GOPATH`:
52 |
53 | 0. Install Go 1.17
54 |
55 | ```
56 | $ go get golang.org/dl/go1.17.1
57 | # Assuming your GOPATH is default (~/go), Go 1.17.1 will be installed in ~/go/bin
58 | $ ~/go/bin/go1.17.1 version
59 | go version go1.17.1 linux/amd64
60 | ```
61 |
62 | 1. Clone this repository:
63 |
64 | ```
65 | $ git clone github.com/librespeed/speedtest-go
66 | ```
67 |
68 | 2. Build
69 | ```
70 | # Change current working directory to the repository
71 | $ cd speedtest-go
72 | # Compile
73 | $ go build -ldflags "-w -s" -trimpath -o speedtest main.go
74 | ```
75 |
76 | 3. Copy the `assets` directory, `settings.toml` file along with the compiled `speedtest` binary into a single directory
77 |
78 | 4. If you have telemetry enabled,
79 | - For PostgreSQL/MySQL, create database and import the corresponding `.sql` file under `database/{postgresql,mysql}`
80 |
81 | ```
82 | # assume you have already created a database named `speedtest` under current user
83 | $ psql speedtest < database/postgresql/telemetry_postgresql.sql
84 | ```
85 |
86 | - For embedded BoltDB, make sure to define the `database_file` path in `settings.toml`:
87 |
88 | ```
89 | database_file="speedtest.db"
90 | ```
91 |
92 | 5. Put `assets` folder under the same directory as your compiled binary.
93 | - Make sure the font files and JavaScripts are in the `assets` directory
94 | - You can have multiple HTML pages under `assets` directory. They can be access directly under the server root
95 | (e.g. `/example-singleServer-full.html`)
96 | - It's possible to have a default page mapped to `/`, simply put a file named `index.html` under `assets`
97 |
98 | 6. Change `settings.toml` according to your environment:
99 |
100 | ```toml
101 | # bind address, use empty string to bind to all interfaces
102 | bind_address="127.0.0.1"
103 | # backend listen port, default is 8989
104 | listen_port=8989
105 | # proxy protocol port, use 0 to disable
106 | proxyprotocol_port=0
107 | # Server location, use zeroes to fetch from API automatically
108 | server_lat=0
109 | server_lng=0
110 | # ipinfo.io API key, if applicable
111 | ipinfo_api_key=""
112 |
113 | # assets directory path, defaults to `assets` in the same directory
114 | # if the path cannot be found, embedded default assets will be used
115 | assets_path="./assets"
116 |
117 | # password for logging into statistics page, change this to enable stats page
118 | statistics_password="PASSWORD"
119 | # redact IP addresses
120 | redact_ip_addresses=false
121 |
122 | # database type for statistics data, currently supports: none, memory, bolt, mysql, postgresql
123 | # if none is specified, no telemetry/stats will be recorded, and no result PNG will be generated
124 | database_type="postgresql"
125 | database_hostname="localhost"
126 | database_name="speedtest"
127 | database_username="postgres"
128 | database_password=""
129 |
130 | # if you use `bolt` as database, set database_file to database file location
131 | database_file="speedtest.db"
132 |
133 | # TLS and HTTP/2 settings. TLS is required for HTTP/2
134 | enable_tls=false
135 | enable_http2=false
136 |
137 | # if you use HTTP/2 or TLS, you need to prepare certificates and private keys
138 | # tls_cert_file="cert.pem"
139 | # tls_key_file="privkey.pem"
140 | ```
141 |
142 | ## Differences between Go and PHP implementation and caveats
143 |
144 | - Since there is no CGo-free SQLite implementation available, I've opted to use [BoltDB](https://github.com/etcd-io/bbolt)
145 | instead, as an embedded database alternative to SQLite
146 | - Test IDs are generated ULID, there is no option to change them to plain ID
147 | - You can use the same HTML template from the PHP implementation
148 | - Server location can be defined in settings
149 | - There might be a slight delay on program start if your Internet connection is slow. That's because the program will
150 | attempt to fetch your current network's ISP info for distance calculation between your network and the speed test client's.
151 | This action will only be taken once, and cached for later use.
152 |
153 | ## License
154 | Copyright (C) 2016-2020 Federico Dossena
155 | Copyright (C) 2020 Maddie Zhan
156 |
157 | This program is free software: you can redistribute it and/or modify
158 | it under the terms of the GNU Lesser General Public License as published by
159 | the Free Software Foundation, either version 3 of the License, or
160 | (at your option) any later version.
161 |
162 | This program is distributed in the hope that it will be useful,
163 | but WITHOUT ANY WARRANTY; without even the implied warranty of
164 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
165 | GNU General Public License for more details.
166 |
167 | You should have received a copy of the GNU Lesser General Public License
168 | along with this program. If not, see .
--------------------------------------------------------------------------------
/web/assets/example-multipleServers-pretty.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | LibreSpeed Example
8 |
9 |
100 |
101 |
205 |
206 |
207 |
260 |
261 |
262 |
263 |
--------------------------------------------------------------------------------
/web/web.go:
--------------------------------------------------------------------------------
1 | package web
2 |
3 | import (
4 | "embed"
5 | "encoding/json"
6 | "io"
7 | "io/fs"
8 | "io/ioutil"
9 | "net"
10 | "net/http"
11 | "os"
12 | "regexp"
13 | "strconv"
14 | "strings"
15 |
16 | "github.com/go-chi/chi/v5"
17 | "github.com/go-chi/chi/v5/middleware"
18 | "github.com/go-chi/cors"
19 | "github.com/go-chi/render"
20 | "github.com/pires/go-proxyproto"
21 | log "github.com/sirupsen/logrus"
22 |
23 | "github.com/librespeed/speedtest/config"
24 | "github.com/librespeed/speedtest/results"
25 | )
26 |
27 | const (
28 | // chunk size is 1 mib
29 | chunkSize = 1048576
30 | )
31 |
32 | //go:embed assets
33 | var defaultAssets embed.FS
34 |
35 | var (
36 | // generate random data for download test on start to minimize runtime overhead
37 | randomData = getRandomData(chunkSize)
38 | )
39 |
40 | func ListenAndServe(conf *config.Config) error {
41 | r := chi.NewRouter()
42 | r.Use(middleware.RealIP)
43 | r.Use(middleware.GetHead)
44 |
45 | cs := cors.New(cors.Options{
46 | AllowedOrigins: []string{"*"},
47 | AllowedMethods: []string{"GET", "POST", "OPTIONS", "HEAD"},
48 | AllowedHeaders: []string{"*"},
49 | })
50 |
51 | r.Use(cs.Handler)
52 | r.Use(middleware.NoCache)
53 | r.Use(middleware.Recoverer)
54 |
55 | var assetFS http.FileSystem
56 | if fi, err := os.Stat(conf.AssetsPath); os.IsNotExist(err) || !fi.IsDir() {
57 | log.Warnf("Configured asset path %s does not exist or is not a directory, using default assets", conf.AssetsPath)
58 | sub, err := fs.Sub(defaultAssets, "assets")
59 | if err != nil {
60 | log.Fatalf("Failed when processing default assets: %s", err)
61 | }
62 | assetFS = http.FS(sub)
63 | } else {
64 | assetFS = justFilesFilesystem{fs: http.Dir(conf.AssetsPath), readDirBatchSize: 2}
65 | }
66 |
67 | r.Get(conf.BaseURL+"/*", pages(assetFS, conf.BaseURL))
68 | r.HandleFunc(conf.BaseURL+"/empty", empty)
69 | r.HandleFunc(conf.BaseURL+"/backend/empty", empty)
70 | r.Get(conf.BaseURL+"/garbage", garbage)
71 | r.Get(conf.BaseURL+"/backend/garbage", garbage)
72 | r.Get(conf.BaseURL+"/getIP", getIP)
73 | r.Get(conf.BaseURL+"/backend/getIP", getIP)
74 | r.Get(conf.BaseURL+"/results", results.DrawPNG)
75 | r.Get(conf.BaseURL+"/results/", results.DrawPNG)
76 | r.Get(conf.BaseURL+"/backend/results", results.DrawPNG)
77 | r.Get(conf.BaseURL+"/backend/results/", results.DrawPNG)
78 | r.Post(conf.BaseURL+"/results/telemetry", results.Record)
79 | r.Post(conf.BaseURL+"/backend/results/telemetry", results.Record)
80 | r.HandleFunc(conf.BaseURL+"/stats", results.Stats)
81 | r.HandleFunc(conf.BaseURL+"/backend/stats", results.Stats)
82 |
83 | // PHP frontend default values compatibility
84 | r.HandleFunc(conf.BaseURL+"/empty.php", empty)
85 | r.HandleFunc(conf.BaseURL+"/backend/empty.php", empty)
86 | r.Get(conf.BaseURL+"/garbage.php", garbage)
87 | r.Get(conf.BaseURL+"/backend/garbage.php", garbage)
88 | r.Get(conf.BaseURL+"/getIP.php", getIP)
89 | r.Get(conf.BaseURL+"/backend/getIP.php", getIP)
90 | r.Post(conf.BaseURL+"/results/telemetry.php", results.Record)
91 | r.Post(conf.BaseURL+"/backend/results/telemetry.php", results.Record)
92 | r.HandleFunc(conf.BaseURL+"/stats.php", results.Stats)
93 | r.HandleFunc(conf.BaseURL+"/backend/stats.php", results.Stats)
94 |
95 | go listenProxyProtocol(conf, r)
96 |
97 | return startListener(conf, r)
98 | }
99 |
100 | func listenProxyProtocol(conf *config.Config, r *chi.Mux) {
101 | if conf.ProxyProtocolPort != "0" {
102 | addr := net.JoinHostPort(conf.BindAddress, conf.ProxyProtocolPort)
103 | l, err := net.Listen("tcp", addr)
104 | if err != nil {
105 | log.Fatalf("Cannot listen on proxy protocol port %s: %s", conf.ProxyProtocolPort, err)
106 | }
107 |
108 | pl := &proxyproto.Listener{Listener: l}
109 | defer pl.Close()
110 |
111 | log.Infof("Starting proxy protocol listener on %s", addr)
112 | log.Fatal(http.Serve(pl, r))
113 | }
114 | }
115 |
116 | func pages(fs http.FileSystem, BaseURL string) http.HandlerFunc {
117 | var removeBaseURL *regexp.Regexp
118 | if BaseURL != "" {
119 | removeBaseURL = regexp.MustCompile("^" + BaseURL + "/")
120 | }
121 | fn := func(w http.ResponseWriter, r *http.Request) {
122 | if BaseURL != "" {
123 | r.URL.Path = removeBaseURL.ReplaceAllString(r.URL.Path, "/")
124 | }
125 | if r.RequestURI == "/" {
126 | r.RequestURI = "/index.html"
127 | }
128 |
129 | http.FileServer(fs).ServeHTTP(w, r)
130 | }
131 |
132 | return fn
133 | }
134 |
135 | func empty(w http.ResponseWriter, r *http.Request) {
136 | _, err := io.Copy(ioutil.Discard, r.Body)
137 | if err != nil {
138 | w.WriteHeader(http.StatusBadRequest)
139 | return
140 | }
141 | _ = r.Body.Close()
142 |
143 | w.Header().Set("Connection", "keep-alive")
144 | w.WriteHeader(http.StatusOK)
145 | }
146 |
147 | func garbage(w http.ResponseWriter, r *http.Request) {
148 | w.Header().Set("Content-Description", "File Transfer")
149 | w.Header().Set("Content-Type", "application/octet-stream")
150 | w.Header().Set("Content-Disposition", "attachment; filename=random.dat")
151 | w.Header().Set("Content-Transfer-Encoding", "binary")
152 |
153 | // chunk size set to 4 by default
154 | chunks := 4
155 |
156 | ckSize := r.FormValue("ckSize")
157 | if ckSize != "" {
158 | i, err := strconv.ParseInt(ckSize, 10, 64)
159 | if err != nil {
160 | log.Errorf("Invalid chunk size: %s", ckSize)
161 | log.Warnf("Will use default value %d", chunks)
162 | } else {
163 | // limit max chunk size to 1024
164 | if i > 1024 {
165 | chunks = 1024
166 | } else {
167 | chunks = int(i)
168 | }
169 | }
170 | }
171 |
172 | for i := 0; i < chunks; i++ {
173 | if _, err := w.Write(randomData); err != nil {
174 | log.Errorf("Error writing back to client at chunk number %d: %s", i, err)
175 | break
176 | }
177 | }
178 | }
179 |
180 | func getIP(w http.ResponseWriter, r *http.Request) {
181 | var ret results.Result
182 |
183 | clientIP := r.RemoteAddr
184 | clientIP = strings.ReplaceAll(clientIP, "::ffff:", "")
185 |
186 | ip, _, err := net.SplitHostPort(r.RemoteAddr)
187 | if err == nil {
188 | clientIP = ip
189 | }
190 |
191 | isSpecialIP := true
192 | switch {
193 | case clientIP == "::1":
194 | ret.ProcessedString = clientIP + " - localhost IPv6 access"
195 | case strings.HasPrefix(clientIP, "fe80:"):
196 | ret.ProcessedString = clientIP + " - link-local IPv6 access"
197 | case strings.HasPrefix(clientIP, "127."):
198 | ret.ProcessedString = clientIP + " - localhost IPv4 access"
199 | case strings.HasPrefix(clientIP, "10."):
200 | ret.ProcessedString = clientIP + " - private IPv4 access"
201 | case regexp.MustCompile(`^172\.(1[6-9]|2\d|3[01])\.`).MatchString(clientIP):
202 | ret.ProcessedString = clientIP + " - private IPv4 access"
203 | case strings.HasPrefix(clientIP, "192.168"):
204 | ret.ProcessedString = clientIP + " - private IPv4 access"
205 | case strings.HasPrefix(clientIP, "169.254"):
206 | ret.ProcessedString = clientIP + " - link-local IPv4 access"
207 | case regexp.MustCompile(`^100\.([6-9][0-9]|1[0-2][0-7])\.`).MatchString(clientIP):
208 | ret.ProcessedString = clientIP + " - CGNAT IPv4 access"
209 | default:
210 | isSpecialIP = false
211 | }
212 |
213 | if isSpecialIP {
214 | b, _ := json.Marshal(&ret)
215 | if _, err := w.Write(b); err != nil {
216 | log.Errorf("Error writing to client: %s", err)
217 | }
218 | return
219 | }
220 |
221 | getISPInfo := r.FormValue("isp") == "true"
222 | distanceUnit := r.FormValue("distance")
223 |
224 | ret.ProcessedString = clientIP
225 |
226 | if getISPInfo {
227 | ispInfo := getIPInfo(clientIP)
228 | ret.RawISPInfo = ispInfo
229 |
230 | removeRegexp := regexp.MustCompile(`AS\d+\s`)
231 | isp := removeRegexp.ReplaceAllString(ispInfo.Organization, "")
232 |
233 | if isp == "" {
234 | isp = "Unknown ISP"
235 | }
236 |
237 | if ispInfo.Country != "" {
238 | isp += ", " + ispInfo.Country
239 | }
240 |
241 | if ispInfo.Location != "" {
242 | isp += " (" + calculateDistance(ispInfo.Location, distanceUnit) + ")"
243 | }
244 |
245 | ret.ProcessedString += " - " + isp
246 | }
247 |
248 | render.JSON(w, r, ret)
249 | }
250 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER 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 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/web/assets/example-singleServer-chart.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | LibreSpeed Example
6 |
7 |
39 |
40 |
41 |
238 |
239 |
240 |
241 |
This HTML5 Speedtest server is configured with telemetry enabled.
325 |
What data we collect
326 |
327 | At the end of the test, the following data is collected and stored:
328 |
329 |
Test ID
330 |
Time of testing
331 |
Test results (download and upload speed, ping and jitter)
332 |
IP address
333 |
ISP information
334 |
Approximate location (inferred from IP address, not GPS)
335 |
User agent and browser locale
336 |
Test log (contains no personal information)
337 |
338 |
339 |
How we use the data
340 |
341 | Data collected through this service is used to:
342 |
343 |
Allow sharing of test results (sharable image for forums, etc.)
344 |
To improve the service offered to you (for instance, to detect problems on our side)
345 |
346 | No personal information is disclosed to third parties.
347 |
348 |
Your consent
349 |
350 | By starting the test, you consent to the terms of this privacy policy.
351 |
352 |
Data removal
353 |
354 | If you want to have your information deleted, you need to provide either the ID of the test or your IP address. This is the only way to identify your data, without this information we won't be able to comply with your request.
This HTML5 Speedtest server is configured with telemetry enabled.
451 |
What data we collect
452 |
453 | At the end of the test, the following data is collected and stored:
454 |
455 |
Test ID
456 |
Time of testing
457 |
Test results (download and upload speed, ping and jitter)
458 |
IP address
459 |
ISP information
460 |
Approximate location (inferred from IP address, not GPS)
461 |
User agent and browser locale
462 |
Test log (contains no personal information)
463 |
464 |
465 |
How we use the data
466 |
467 | Data collected through this service is used to:
468 |
469 |
Allow sharing of test results (sharable image for forums, etc.)
470 |
To improve the service offered to you (for instance, to detect problems on our side)
471 |
472 | No personal information is disclosed to third parties.
473 |
474 |
Your consent
475 |
476 | By starting the test, you consent to the terms of this privacy policy.
477 |
478 |
Data removal
479 |
480 | If you want to have your information deleted, you need to provide either the ID of the test or your IP address. This is the only way to identify your data, without this information we won't be able to comply with your request.
489 |
490 |
491 |
--------------------------------------------------------------------------------
/web/assets/speedtest.js:
--------------------------------------------------------------------------------
1 | /*
2 | LibreSpeed - Main
3 | by Federico Dossena
4 | https://github.com/librespeed/speedtest/
5 | GNU LGPLv3 License
6 | */
7 |
8 | /*
9 | This is the main interface between your webpage and the speedtest.
10 | It hides the speedtest web worker to the page, and provides many convenient functions to control the test.
11 |
12 | The best way to learn how to use this is to look at the basic example, but here's some documentation.
13 |
14 | To initialize the test, create a new Speedtest object:
15 | var s=new Speedtest();
16 | Now you can think of this as a finite state machine. These are the states (use getState() to see them):
17 | - 0: here you can change the speedtest settings (such as test duration) with the setParameter("parameter",value) method. From here you can either start the test using start() (goes to state 3) or you can add multiple test points using addTestPoint(server) or addTestPoints(serverList) (goes to state 1). Additionally, this is the perfect moment to set up callbacks for the onupdate(data) and onend(aborted) events.
18 | - 1: here you can add test points. You only need to do this if you want to use multiple test points.
19 | A server is defined as an object like this:
20 | {
21 | name: "User friendly name",
22 | server:"http://yourBackend.com/", <---- URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
23 | dlURL:"garbage.php" <----- path to garbage.php or its replacement on the server
24 | ulURL:"empty.php" <----- path to empty.php or its replacement on the server
25 | pingURL:"empty.php" <----- path to empty.php or its replacement on the server. This is used to ping the server by this selector
26 | getIpURL:"getIP.php" <----- path to getIP.php or its replacement on the server
27 | }
28 | While in state 1, you can only add test points, you cannot change the test settings. When you're done, use selectServer(callback) to select the test point with the lowest ping. This is asynchronous, when it's done, it will call your callback function and move to state 2. Calling setSelectedServer(server) will manually select a server and move to state 2.
29 | - 2: test point selected, ready to start the test. Use start() to begin, this will move to state 3
30 | - 3: test running. Here, your onupdate event calback will be called periodically, with data coming from the worker about speed and progress. A data object will be passed to your onupdate function, with the following items:
31 | - dlStatus: download speed in mbps
32 | - ulStatus: upload speed in mbps
33 | - pingStatus: ping in ms
34 | - jitterStatus: jitter in ms
35 | - dlProgress: progress of the download test as a float 0-1
36 | - ulProgress: progress of the upload test as a float 0-1
37 | - pingProgress: progress of the ping/jitter test as a float 0-1
38 | - testState: state of the test (-1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=aborted)
39 | - clientIp: IP address of the client performing the test (and optionally ISP and distance)
40 | At the end of the test, the onend function will be called, with a boolean specifying whether the test was aborted or if it ended normally.
41 | The test can be aborted at any time with abort().
42 | At the end of the test, it will move to state 4
43 | - 4: test finished. You can run it again by calling start() if you want.
44 | */
45 |
46 | function Speedtest() {
47 | this._serverList = []; //when using multiple points of test, this is a list of test points
48 | this._selectedServer = null; //when using multiple points of test, this is the selected server
49 | this._settings = {}; //settings for the speedtest worker
50 | this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
51 | console.log(
52 | "LibreSpeed by Federico Dossena v5.2.4 - https://github.com/librespeed/speedtest"
53 | );
54 | }
55 |
56 | Speedtest.prototype = {
57 | constructor: Speedtest,
58 | /**
59 | * Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
60 | */
61 | getState: function() {
62 | return this._state;
63 | },
64 | /**
65 | * Change one of the test settings from their defaults.
66 | * - parameter: string with the name of the parameter that you want to set
67 | * - value: new value for the parameter
68 | *
69 | * Invalid values or nonexistant parameters will be ignored by the speedtest worker.
70 | */
71 | setParameter: function(parameter, value) {
72 | if (this._state == 3)
73 | throw "You cannot change the test settings while running the test";
74 | this._settings[parameter] = value;
75 | if(parameter === "telemetry_extra"){
76 | this._originalExtra=this._settings.telemetry_extra;
77 | }
78 | },
79 | /**
80 | * Used internally to check if a server object contains all the required elements.
81 | * Also fixes the server URL if needed.
82 | */
83 | _checkServerDefinition: function(server) {
84 | try {
85 | if (typeof server.name !== "string")
86 | throw "Name string missing from server definition (name)";
87 | if (typeof server.server !== "string")
88 | throw "Server address string missing from server definition (server)";
89 | if (server.server.charAt(server.server.length - 1) != "/")
90 | server.server += "/";
91 | if (server.server.indexOf("//") == 0)
92 | server.server = location.protocol + server.server;
93 | if (typeof server.dlURL !== "string")
94 | throw "Download URL string missing from server definition (dlURL)";
95 | if (typeof server.ulURL !== "string")
96 | throw "Upload URL string missing from server definition (ulURL)";
97 | if (typeof server.pingURL !== "string")
98 | throw "Ping URL string missing from server definition (pingURL)";
99 | if (typeof server.getIpURL !== "string")
100 | throw "GetIP URL string missing from server definition (getIpURL)";
101 | } catch (e) {
102 | throw "Invalid server definition";
103 | }
104 | },
105 | /**
106 | * Add a test point (multiple points of test)
107 | * server: the server to be added as an object. Must contain the following elements:
108 | * {
109 | * name: "User friendly name",
110 | * server:"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
111 | * dlURL:"garbage.php" path to garbage.php or its replacement on the server
112 | * ulURL:"empty.php" path to empty.php or its replacement on the server
113 | * pingURL:"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
114 | * getIpURL:"getIP.php" path to getIP.php or its replacement on the server
115 | * }
116 | */
117 | addTestPoint: function(server) {
118 | this._checkServerDefinition(server);
119 | if (this._state == 0) this._state = 1;
120 | if (this._state != 1) throw "You can't add a server after server selection";
121 | this._settings.mpot = true;
122 | this._serverList.push(server);
123 | },
124 | /**
125 | * Same as addTestPoint, but you can pass an array of servers
126 | */
127 | addTestPoints: function(list) {
128 | for (var i = 0; i < list.length; i++) this.addTestPoint(list[i]);
129 | },
130 | /**
131 | * Load a JSON server list from URL (multiple points of test)
132 | * url: the url where the server list can be fetched. Must be an array with objects containing the following elements:
133 | * {
134 | * "name": "User friendly name",
135 | * "server":"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
136 | * "dlURL":"garbage.php" path to garbage.php or its replacement on the server
137 | * "ulURL":"empty.php" path to empty.php or its replacement on the server
138 | * "pingURL":"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
139 | * "getIpURL":"getIP.php" path to getIP.php or its replacement on the server
140 | * }
141 | * result: callback to be called when the list is loaded correctly. An array with the loaded servers will be passed to this function, or null if it failed
142 | */
143 | loadServerList: function(url,result) {
144 | if (this._state == 0) this._state = 1;
145 | if (this._state != 1) throw "You can't add a server after server selection";
146 | this._settings.mpot = true;
147 | var xhr = new XMLHttpRequest();
148 | xhr.onload = function(){
149 | try{
150 | var servers=JSON.parse(xhr.responseText);
151 | for(var i=0;i= 3)
191 | throw "You can't select a server while the test is running";
192 | }
193 | if (this._selectServerCalled) throw "selectServer already called"; else this._selectServerCalled=true;
194 | /*this function goes through a list of servers. For each server, the ping is measured, then the server with the function selected is called with the best server, or null if all the servers were down.
195 | */
196 | var select = function(serverList, selected) {
197 | //pings the specified URL, then calls the function result. Result will receive a parameter which is either the time it took to ping the URL, or -1 if something went wrong.
198 | var PING_TIMEOUT = 2000;
199 | var USE_PING_TIMEOUT = true; //will be disabled on unsupported browsers
200 | if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) {
201 | //IE11 doesn't support XHR timeout
202 | USE_PING_TIMEOUT = false;
203 | }
204 | var ping = function(url, rtt) {
205 | url += (url.match(/\?/) ? "&" : "?") + "cors=true";
206 | var xhr = new XMLHttpRequest();
207 | var t = new Date().getTime();
208 | xhr.onload = function() {
209 | if (xhr.responseText.length == 0) {
210 | //we expect an empty response
211 | var instspd = new Date().getTime() - t; //rough timing estimate
212 | try {
213 | //try to get more accurate timing using performance API
214 | var p = performance.getEntriesByName(url);
215 | p = p[p.length - 1];
216 | var d = p.responseStart - p.requestStart;
217 | if (d <= 0) d = p.duration;
218 | if (d > 0 && d < instspd) instspd = d;
219 | } catch (e) {}
220 | rtt(instspd);
221 | } else rtt(-1);
222 | }.bind(this);
223 | xhr.onerror = function() {
224 | rtt(-1);
225 | }.bind(this);
226 | xhr.open("GET", url);
227 | if (USE_PING_TIMEOUT) {
228 | try {
229 | xhr.timeout = PING_TIMEOUT;
230 | xhr.ontimeout = xhr.onerror;
231 | } catch (e) {}
232 | }
233 | xhr.send();
234 | }.bind(this);
235 |
236 | //this function repeatedly pings a server to get a good estimate of the ping. When it's done, it calls the done function without parameters. At the end of the execution, the server will have a new parameter called pingT, which is either the best ping we got from the server or -1 if something went wrong.
237 | var PINGS = 3, //up to 3 pings are performed, unless the server is down...
238 | SLOW_THRESHOLD = 500; //...or one of the pings is above this threshold
239 | var checkServer = function(server, done) {
240 | var i = 0;
241 | server.pingT = -1;
242 | if (server.server.indexOf(location.protocol) == -1) done();
243 | else {
244 | var nextPing = function() {
245 | if (i++ == PINGS) {
246 | done();
247 | return;
248 | }
249 | ping(
250 | server.server + server.pingURL,
251 | function(t) {
252 | if (t >= 0) {
253 | if (t < server.pingT || server.pingT == -1) server.pingT = t;
254 | if (t < SLOW_THRESHOLD) nextPing();
255 | else done();
256 | } else done();
257 | }.bind(this)
258 | );
259 | }.bind(this);
260 | nextPing();
261 | }
262 | }.bind(this);
263 | //check servers in list, one by one
264 | var i = 0;
265 | var done = function() {
266 | var bestServer = null;
267 | for (var i = 0; i < serverList.length; i++) {
268 | if (
269 | serverList[i].pingT != -1 &&
270 | (bestServer == null || serverList[i].pingT < bestServer.pingT)
271 | )
272 | bestServer = serverList[i];
273 | }
274 | selected(bestServer);
275 | }.bind(this);
276 | var nextServer = function() {
277 | if (i == serverList.length) {
278 | done();
279 | return;
280 | }
281 | checkServer(serverList[i++], nextServer);
282 | }.bind(this);
283 | nextServer();
284 | }.bind(this);
285 |
286 | //parallel server selection
287 | var CONCURRENCY = 6;
288 | var serverLists = [];
289 | for (var i = 0; i < CONCURRENCY; i++) {
290 | serverLists[i] = [];
291 | }
292 | for (var i = 0; i < this._serverList.length; i++) {
293 | serverLists[i % CONCURRENCY].push(this._serverList[i]);
294 | }
295 | var completed = 0;
296 | var bestServer = null;
297 | for (var i = 0; i < CONCURRENCY; i++) {
298 | select(
299 | serverLists[i],
300 | function(server) {
301 | if (server != null) {
302 | if (bestServer == null || server.pingT < bestServer.pingT)
303 | bestServer = server;
304 | }
305 | completed++;
306 | if (completed == CONCURRENCY) {
307 | this._selectedServer = bestServer;
308 | this._state = 2;
309 | if (result) result(bestServer);
310 | }
311 | }.bind(this)
312 | );
313 | }
314 | },
315 | /**
316 | * Starts the test.
317 | * During the test, the onupdate(data) callback function will be called periodically with data from the worker.
318 | * At the end of the test, the onend(aborted) function will be called with a boolean telling you if the test was aborted or if it ended normally.
319 | */
320 | start: function() {
321 | if (this._state == 3) throw "Test already running";
322 | this.worker = new Worker("speedtest_worker.js?r=" + Math.random());
323 | this.worker.onmessage = function(e) {
324 | if (e.data === this._prevData) return;
325 | else this._prevData = e.data;
326 | var data = JSON.parse(e.data);
327 | try {
328 | if (this.onupdate) this.onupdate(data);
329 | } catch (e) {
330 | console.error("Speedtest onupdate event threw exception: " + e);
331 | }
332 | if (data.testState >= 4) {
333 | clearInterval(this.updater);
334 | this._state = 4;
335 | try {
336 | if (this.onend) this.onend(data.testState == 5);
337 | } catch (e) {
338 | console.error("Speedtest onend event threw exception: " + e);
339 | }
340 | }
341 | }.bind(this);
342 | this.updater = setInterval(
343 | function() {
344 | this.worker.postMessage("status");
345 | }.bind(this),
346 | 200
347 | );
348 | if (this._state == 1)
349 | throw "When using multiple points of test, you must call selectServer before starting the test";
350 | if (this._state == 2) {
351 | this._settings.url_dl =
352 | this._selectedServer.server + this._selectedServer.dlURL;
353 | this._settings.url_ul =
354 | this._selectedServer.server + this._selectedServer.ulURL;
355 | this._settings.url_ping =
356 | this._selectedServer.server + this._selectedServer.pingURL;
357 | this._settings.url_getIp =
358 | this._selectedServer.server + this._selectedServer.getIpURL;
359 | if (typeof this._originalExtra !== "undefined") {
360 | this._settings.telemetry_extra = JSON.stringify({
361 | server: this._selectedServer.name,
362 | extra: this._originalExtra
363 | });
364 | } else
365 | this._settings.telemetry_extra = JSON.stringify({
366 | server: this._selectedServer.name
367 | });
368 | }
369 | this._state = 3;
370 | this.worker.postMessage("start " + JSON.stringify(this._settings));
371 | },
372 | /**
373 | * Aborts the test while it's running.
374 | */
375 | abort: function() {
376 | if (this._state < 3) throw "You cannot abort a test that's not started yet";
377 | if (this._state < 4) this.worker.postMessage("abort");
378 | }
379 | };
380 |
--------------------------------------------------------------------------------
/web/assets/speedtest_worker.js:
--------------------------------------------------------------------------------
1 | /*
2 | LibreSpeed - Worker
3 | by Federico Dossena
4 | https://github.com/librespeed/speedtest/
5 | GNU LGPLv3 License
6 | */
7 |
8 | // data reported to main thread
9 | var testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
10 | var dlStatus = ""; // download speed in megabit/s with 2 decimal digits
11 | var ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
12 | var pingStatus = ""; // ping in milliseconds with 2 decimal digits
13 | var jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
14 | var clientIp = ""; // client's IP address as reported by getIP.php
15 | var dlProgress = 0; //progress of download test 0-1
16 | var ulProgress = 0; //progress of upload test 0-1
17 | var pingProgress = 0; //progress of ping+jitter test 0-1
18 | var testId = null; //test ID (sent back by telemetry if used, null otherwise)
19 |
20 | var log = ""; //telemetry log
21 | function tlog(s) {
22 | if (settings.telemetry_level >= 2) {
23 | log += Date.now() + ": " + s + "\n";
24 | }
25 | }
26 | function tverb(s) {
27 | if (settings.telemetry_level >= 3) {
28 | log += Date.now() + ": " + s + "\n";
29 | }
30 | }
31 | function twarn(s) {
32 | if (settings.telemetry_level >= 2) {
33 | log += Date.now() + " WARN: " + s + "\n";
34 | }
35 | console.warn(s);
36 | }
37 |
38 | // test settings. can be overridden by sending specific values with the start command
39 | var settings = {
40 | mpot: false, //set to true when in MPOT mode
41 | test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
42 | time_ul_max: 15, // max duration of upload test in seconds
43 | time_dl_max: 15, // max duration of download test in seconds
44 | time_auto: true, // if set to true, tests will take less time on faster connections
45 | time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
46 | time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
47 | count_ping: 10, // number of pings to perform in ping test
48 | url_dl: "backend/garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
49 | url_ul: "backend/empty.php", // path to an empty file, used for upload test. must be relative to this js file
50 | url_ping: "backend/empty.php", // path to an empty file, used for ping test. must be relative to this js file
51 | url_getIp: "backend/getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
52 | getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
53 | getIp_ispInfo_distance: "km", //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
54 | xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
55 | xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
56 | xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
57 | xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
58 | xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
59 | xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
60 | garbagePhp_chunkSize: 100, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
61 | enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
62 | ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
63 | overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
64 | useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
65 | telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
66 | url_telemetry: "results/telemetry.php", // path to the script that adds telemetry data to the database
67 | telemetry_extra: "", //extra data that can be passed to the telemetry through the settings
68 | forceIE11Workaround: false //when set to true, it will foce the IE11 upload test on all browsers. Debug only
69 | };
70 |
71 | var xhr = null; // array of currently active xhr requests
72 | var interval = null; // timer used in tests
73 | var test_pointer = 0; //pointer to the next test to run inside settings.test_order
74 |
75 | /*
76 | this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
77 | */
78 | function url_sep(url) {
79 | return url.match(/\?/) ? "&" : "?";
80 | }
81 |
82 | /*
83 | listener for commands from main thread to this worker.
84 | commands:
85 | -status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
86 | -abort: aborts the current test
87 | -start: starts the test. optionally, settings can be passed as JSON.
88 | example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
89 | */
90 | this.addEventListener("message", function(e) {
91 | var params = e.data.split(" ");
92 | if (params[0] === "status") {
93 | // return status
94 | postMessage(
95 | JSON.stringify({
96 | testState: testState,
97 | dlStatus: dlStatus,
98 | ulStatus: ulStatus,
99 | pingStatus: pingStatus,
100 | clientIp: clientIp,
101 | jitterStatus: jitterStatus,
102 | dlProgress: dlProgress,
103 | ulProgress: ulProgress,
104 | pingProgress: pingProgress,
105 | testId: testId
106 | })
107 | );
108 | }
109 | if (params[0] === "start" && testState === -1) {
110 | // start new test
111 | testState = 0;
112 | try {
113 | // parse settings, if present
114 | var s = {};
115 | try {
116 | var ss = e.data.substring(5);
117 | if (ss) s = JSON.parse(ss);
118 | } catch (e) {
119 | twarn("Error parsing custom settings JSON. Please check your syntax");
120 | }
121 | //copy custom settings
122 | for (var key in s) {
123 | if (typeof settings[key] !== "undefined") settings[key] = s[key];
124 | else twarn("Unknown setting ignored: " + key);
125 | }
126 | var ua = navigator.userAgent;
127 | // quirks for specific browsers. apply only if not overridden. more may be added in future releases
128 | if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
129 | if (/Firefox.(\d+\.\d+)/i.test(ua)) {
130 | if (typeof s.ping_allowPerformanceApi === "undefined") {
131 | // ff performance API sucks
132 | settings.ping_allowPerformanceApi = false;
133 | }
134 | }
135 | if (/Edge.(\d+\.\d+)/i.test(ua)) {
136 | if (typeof s.xhr_dlMultistream === "undefined") {
137 | // edge more precise with 3 download streams
138 | settings.xhr_dlMultistream = 3;
139 | }
140 | }
141 | if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
142 | if (typeof s.xhr_dlMultistream === "undefined") {
143 | // chrome more precise with 5 streams
144 | settings.xhr_dlMultistream = 5;
145 | }
146 | }
147 | }
148 | if (/Edge.(\d+\.\d+)/i.test(ua)) {
149 | //Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
150 | settings.forceIE11Workaround = true;
151 | }
152 | if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
153 | //PS4 browser has the same bug as IE11/Edge
154 | settings.forceIE11Workaround = true;
155 | }
156 | if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
157 | //cheap af
158 | //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
159 | settings.xhr_ul_blob_megabytes = 4;
160 | }
161 | if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
162 | //Safari also needs the IE11 workaround but only for the MPOT version
163 | settings.forceIE11Workaround = true;
164 | }
165 | //telemetry_level has to be parsed and not just copied
166 | if (typeof s.telemetry_level !== "undefined") settings.telemetry_level = s.telemetry_level === "basic" ? 1 : s.telemetry_level === "full" ? 2 : s.telemetry_level === "debug" ? 3 : 0; // telemetry level
167 | //transform test_order to uppercase, just in case
168 | settings.test_order = settings.test_order.toUpperCase();
169 | } catch (e) {
170 | twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
171 | }
172 | // run the tests
173 | tverb(JSON.stringify(settings));
174 | test_pointer = 0;
175 | var iRun = false,
176 | dRun = false,
177 | uRun = false,
178 | pRun = false;
179 | var runNextTest = function() {
180 | if (testState == 5) return;
181 | if (test_pointer >= settings.test_order.length) {
182 | //test is finished
183 | if (settings.telemetry_level > 0)
184 | sendTelemetry(function(id) {
185 | testState = 4;
186 | if (id != null) testId = id;
187 | });
188 | else testState = 4;
189 | return;
190 | }
191 | switch (settings.test_order.charAt(test_pointer)) {
192 | case "I":
193 | {
194 | test_pointer++;
195 | if (iRun) {
196 | runNextTest();
197 | return;
198 | } else iRun = true;
199 | getIp(runNextTest);
200 | }
201 | break;
202 | case "D":
203 | {
204 | test_pointer++;
205 | if (dRun) {
206 | runNextTest();
207 | return;
208 | } else dRun = true;
209 | testState = 1;
210 | dlTest(runNextTest);
211 | }
212 | break;
213 | case "U":
214 | {
215 | test_pointer++;
216 | if (uRun) {
217 | runNextTest();
218 | return;
219 | } else uRun = true;
220 | testState = 3;
221 | ulTest(runNextTest);
222 | }
223 | break;
224 | case "P":
225 | {
226 | test_pointer++;
227 | if (pRun) {
228 | runNextTest();
229 | return;
230 | } else pRun = true;
231 | testState = 2;
232 | pingTest(runNextTest);
233 | }
234 | break;
235 | case "_":
236 | {
237 | test_pointer++;
238 | setTimeout(runNextTest, 1000);
239 | }
240 | break;
241 | default:
242 | test_pointer++;
243 | }
244 | };
245 | runNextTest();
246 | }
247 | if (params[0] === "abort") {
248 | // abort command
249 | if (testState >= 4) return;
250 | tlog("manually aborted");
251 | clearRequests(); // stop all xhr activity
252 | runNextTest = null;
253 | if (interval) clearInterval(interval); // clear timer if present
254 | if (settings.telemetry_level > 1) sendTelemetry(function() {});
255 | testState = 5; //set test as aborted
256 | dlStatus = "";
257 | ulStatus = "";
258 | pingStatus = "";
259 | jitterStatus = "";
260 | clientIp = "";
261 | dlProgress = 0;
262 | ulProgress = 0;
263 | pingProgress = 0;
264 | }
265 | });
266 | // stops all XHR activity, aggressively
267 | function clearRequests() {
268 | tverb("stopping pending XHRs");
269 | if (xhr) {
270 | for (var i = 0; i < xhr.length; i++) {
271 | try {
272 | xhr[i].onprogress = null;
273 | xhr[i].onload = null;
274 | xhr[i].onerror = null;
275 | } catch (e) {}
276 | try {
277 | xhr[i].upload.onprogress = null;
278 | xhr[i].upload.onload = null;
279 | xhr[i].upload.onerror = null;
280 | } catch (e) {}
281 | try {
282 | xhr[i].abort();
283 | } catch (e) {}
284 | try {
285 | delete xhr[i];
286 | } catch (e) {}
287 | }
288 | xhr = null;
289 | }
290 | }
291 | // gets client's IP using url_getIp, then calls the done function
292 | var ipCalled = false; // used to prevent multiple accidental calls to getIp
293 | var ispInfo = ""; //used for telemetry
294 | function getIp(done) {
295 | tverb("getIp");
296 | if (ipCalled) return;
297 | else ipCalled = true; // getIp already called?
298 | var startT = new Date().getTime();
299 | xhr = new XMLHttpRequest();
300 | xhr.onload = function() {
301 | tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
302 | try {
303 | var data = JSON.parse(xhr.responseText);
304 | clientIp = data.processedString;
305 | ispInfo = data.rawIspInfo;
306 | } catch (e) {
307 | clientIp = xhr.responseText;
308 | ispInfo = "";
309 | }
310 | done();
311 | };
312 | xhr.onerror = function() {
313 | tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
314 | done();
315 | };
316 | xhr.open("GET", settings.url_getIp + url_sep(settings.url_getIp) + (settings.mpot ? "cors=true&" : "") + (settings.getIp_ispInfo ? "isp=true" + (settings.getIp_ispInfo_distance ? "&distance=" + settings.getIp_ispInfo_distance + "&" : "&") : "&") + "r=" + Math.random(), true);
317 | xhr.send();
318 | }
319 | // download test, calls done function when it's over
320 | var dlCalled = false; // used to prevent multiple accidental calls to dlTest
321 | function dlTest(done) {
322 | tverb("dlTest");
323 | if (dlCalled) return;
324 | else dlCalled = true; // dlTest already called?
325 | var totLoaded = 0.0, // total number of loaded bytes
326 | startT = new Date().getTime(), // timestamp when test was started
327 | bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
328 | graceTimeDone = false, //set to true after the grace time is past
329 | failed = false; // set to true if a stream fails
330 | xhr = [];
331 | // function to create a download stream. streams are slightly delayed so that they will not end at the same time
332 | var testStream = function(i, delay) {
333 | setTimeout(
334 | function() {
335 | if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
336 | tverb("dl test stream started " + i + " " + delay);
337 | var prevLoaded = 0; // number of bytes loaded last time onprogress was called
338 | var x = new XMLHttpRequest();
339 | xhr[i] = x;
340 | xhr[i].onprogress = function(event) {
341 | tverb("dl stream progress event " + i + " " + event.loaded);
342 | if (testState !== 1) {
343 | try {
344 | x.abort();
345 | } catch (e) {}
346 | } // just in case this XHR is still running after the download test
347 | // progress event, add number of new loaded bytes to totLoaded
348 | var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
349 | if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
350 | totLoaded += loadDiff;
351 | prevLoaded = event.loaded;
352 | }.bind(this);
353 | xhr[i].onload = function() {
354 | // the large file has been loaded entirely, start again
355 | tverb("dl stream finished " + i);
356 | try {
357 | xhr[i].abort();
358 | } catch (e) {} // reset the stream data to empty ram
359 | testStream(i, 0);
360 | }.bind(this);
361 | xhr[i].onerror = function() {
362 | // error
363 | tverb("dl stream failed " + i);
364 | if (settings.xhr_ignoreErrors === 0) failed = true; //abort
365 | try {
366 | xhr[i].abort();
367 | } catch (e) {}
368 | delete xhr[i];
369 | if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
370 | }.bind(this);
371 | // send xhr
372 | try {
373 | if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
374 | else xhr[i].responseType = "arraybuffer";
375 | } catch (e) {}
376 | xhr[i].open("GET", settings.url_dl + url_sep(settings.url_dl) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random() + "&ckSize=" + settings.garbagePhp_chunkSize, true); // random string to prevent caching
377 | xhr[i].send();
378 | }.bind(this),
379 | 1 + delay
380 | );
381 | }.bind(this);
382 | // open streams
383 | for (var i = 0; i < settings.xhr_dlMultistream; i++) {
384 | testStream(i, settings.xhr_multistreamDelay * i);
385 | }
386 | // every 200ms, update dlStatus
387 | interval = setInterval(
388 | function() {
389 | tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
390 | var t = new Date().getTime() - startT;
391 | if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
392 | if (t < 200) return;
393 | if (!graceTimeDone) {
394 | if (t > 1000 * settings.time_dlGraceTime) {
395 | if (totLoaded > 0) {
396 | // if the connection is so slow that we didn't get a single chunk yet, do not reset
397 | startT = new Date().getTime();
398 | bonusT = 0;
399 | totLoaded = 0.0;
400 | }
401 | graceTimeDone = true;
402 | }
403 | } else {
404 | var speed = totLoaded / (t / 1000.0);
405 | if (settings.time_auto) {
406 | //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
407 | var bonus = (5.0 * speed) / 100000;
408 | bonusT += bonus > 400 ? 400 : bonus;
409 | }
410 | //update status
411 | dlStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
412 | if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
413 | // test is over, stop streams and timer
414 | if (failed || isNaN(dlStatus)) dlStatus = "Fail";
415 | clearRequests();
416 | clearInterval(interval);
417 | dlProgress = 1;
418 | tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
419 | done();
420 | }
421 | }
422 | }.bind(this),
423 | 200
424 | );
425 | }
426 | // upload test, calls done function whent it's over
427 | var ulCalled = false; // used to prevent multiple accidental calls to ulTest
428 | function ulTest(done) {
429 | tverb("ulTest");
430 | if (ulCalled) return;
431 | else ulCalled = true; // ulTest already called?
432 | // garbage data for upload test
433 | var r = new ArrayBuffer(1048576);
434 | var maxInt = Math.pow(2, 32) - 1;
435 | try {
436 | r = new Uint32Array(r);
437 | for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
438 | } catch (e) {}
439 | var req = [];
440 | var reqsmall = [];
441 | for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
442 | req = new Blob(req);
443 | r = new ArrayBuffer(262144);
444 | try {
445 | r = new Uint32Array(r);
446 | for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
447 | } catch (e) {}
448 | reqsmall.push(r);
449 | reqsmall = new Blob(reqsmall);
450 | var testFunction = function() {
451 | var totLoaded = 0.0, // total number of transmitted bytes
452 | startT = new Date().getTime(), // timestamp when test was started
453 | bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
454 | graceTimeDone = false, //set to true after the grace time is past
455 | failed = false; // set to true if a stream fails
456 | xhr = [];
457 | // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
458 | var testStream = function(i, delay) {
459 | setTimeout(
460 | function() {
461 | if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
462 | tverb("ul test stream started " + i + " " + delay);
463 | var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
464 | var x = new XMLHttpRequest();
465 | xhr[i] = x;
466 | var ie11workaround;
467 | if (settings.forceIE11Workaround) ie11workaround = true;
468 | else {
469 | try {
470 | xhr[i].upload.onprogress;
471 | ie11workaround = false;
472 | } catch (e) {
473 | ie11workaround = true;
474 | }
475 | }
476 | if (ie11workaround) {
477 | // IE11 workarond: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
478 | xhr[i].onload = xhr[i].onerror = function() {
479 | tverb("ul stream progress event (ie11wa)");
480 | totLoaded += reqsmall.size;
481 | testStream(i, 0);
482 | };
483 | xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
484 | try {
485 | xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
486 | } catch (e) {}
487 | //No Content-Type header in MPOT branch because it triggers bugs in some browsers
488 | xhr[i].send(reqsmall);
489 | } else {
490 | // REGULAR version, no workaround
491 | xhr[i].upload.onprogress = function(event) {
492 | tverb("ul stream progress event " + i + " " + event.loaded);
493 | if (testState !== 3) {
494 | try {
495 | x.abort();
496 | } catch (e) {}
497 | } // just in case this XHR is still running after the upload test
498 | // progress event, add number of new loaded bytes to totLoaded
499 | var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
500 | if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
501 | totLoaded += loadDiff;
502 | prevLoaded = event.loaded;
503 | }.bind(this);
504 | xhr[i].upload.onload = function() {
505 | // this stream sent all the garbage data, start again
506 | tverb("ul stream finished " + i);
507 | testStream(i, 0);
508 | }.bind(this);
509 | xhr[i].upload.onerror = function() {
510 | tverb("ul stream failed " + i);
511 | if (settings.xhr_ignoreErrors === 0) failed = true; //abort
512 | try {
513 | xhr[i].abort();
514 | } catch (e) {}
515 | delete xhr[i];
516 | if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
517 | }.bind(this);
518 | // send xhr
519 | xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
520 | try {
521 | xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
522 | } catch (e) {}
523 | //No Content-Type header in MPOT branch because it triggers bugs in some browsers
524 | xhr[i].send(req);
525 | }
526 | }.bind(this),
527 | delay
528 | );
529 | }.bind(this);
530 | // open streams
531 | for (var i = 0; i < settings.xhr_ulMultistream; i++) {
532 | testStream(i, settings.xhr_multistreamDelay * i);
533 | }
534 | // every 200ms, update ulStatus
535 | interval = setInterval(
536 | function() {
537 | tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
538 | var t = new Date().getTime() - startT;
539 | if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
540 | if (t < 200) return;
541 | if (!graceTimeDone) {
542 | if (t > 1000 * settings.time_ulGraceTime) {
543 | if (totLoaded > 0) {
544 | // if the connection is so slow that we didn't get a single chunk yet, do not reset
545 | startT = new Date().getTime();
546 | bonusT = 0;
547 | totLoaded = 0.0;
548 | }
549 | graceTimeDone = true;
550 | }
551 | } else {
552 | var speed = totLoaded / (t / 1000.0);
553 | if (settings.time_auto) {
554 | //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
555 | var bonus = (5.0 * speed) / 100000;
556 | bonusT += bonus > 400 ? 400 : bonus;
557 | }
558 | //update status
559 | ulStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
560 | if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
561 | // test is over, stop streams and timer
562 | if (failed || isNaN(ulStatus)) ulStatus = "Fail";
563 | clearRequests();
564 | clearInterval(interval);
565 | ulProgress = 1;
566 | tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
567 | done();
568 | }
569 | }
570 | }.bind(this),
571 | 200
572 | );
573 | }.bind(this);
574 | if (settings.mpot) {
575 | tverb("Sending POST request before performing upload test");
576 | xhr = [];
577 | xhr[0] = new XMLHttpRequest();
578 | xhr[0].onload = xhr[0].onerror = function() {
579 | tverb("POST request sent, starting upload test");
580 | testFunction();
581 | }.bind(this);
582 | xhr[0].open("POST", settings.url_ul);
583 | xhr[0].send();
584 | } else testFunction();
585 | }
586 | // ping+jitter test, function done is called when it's over
587 | var ptCalled = false; // used to prevent multiple accidental calls to pingTest
588 | function pingTest(done) {
589 | tverb("pingTest");
590 | if (ptCalled) return;
591 | else ptCalled = true; // pingTest already called?
592 | var startT = new Date().getTime(); //when the test was started
593 | var prevT = null; // last time a pong was received
594 | var ping = 0.0; // current ping value
595 | var jitter = 0.0; // current jitter value
596 | var i = 0; // counter of pongs received
597 | var prevInstspd = 0; // last ping time, used for jitter calculation
598 | xhr = [];
599 | // ping function
600 | var doPing = function() {
601 | tverb("ping");
602 | pingProgress = i / settings.count_ping;
603 | prevT = new Date().getTime();
604 | xhr[0] = new XMLHttpRequest();
605 | xhr[0].onload = function() {
606 | // pong
607 | tverb("pong");
608 | if (i === 0) {
609 | prevT = new Date().getTime(); // first pong
610 | } else {
611 | var instspd = new Date().getTime() - prevT;
612 | if (settings.ping_allowPerformanceApi) {
613 | try {
614 | //try to get accurate performance timing using performance api
615 | var p = performance.getEntries();
616 | p = p[p.length - 1];
617 | var d = p.responseStart - p.requestStart;
618 | if (d <= 0) d = p.duration;
619 | if (d > 0 && d < instspd) instspd = d;
620 | } catch (e) {
621 | //if not possible, keep the estimate
622 | tverb("Performance API not supported, using estimate");
623 | }
624 | }
625 | //noticed that some browsers randomly have 0ms ping
626 | if (instspd < 1) instspd = prevInstspd;
627 | if (instspd < 1) instspd = 1;
628 | var instjitter = Math.abs(instspd - prevInstspd);
629 | if (i === 1) ping = instspd;
630 | /* first ping, can't tell jitter yet*/ else {
631 | if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
632 | if (i === 2) jitter = instjitter;
633 | //discard the first jitter measurement because it might be much higher than it should be
634 | else jitter = instjitter > jitter ? jitter * 0.3 + instjitter * 0.7 : jitter * 0.8 + instjitter * 0.2; // update jitter, weighted average. spikes in ping values are given more weight.
635 | }
636 | prevInstspd = instspd;
637 | }
638 | pingStatus = ping.toFixed(2);
639 | jitterStatus = jitter.toFixed(2);
640 | i++;
641 | tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
642 | if (i < settings.count_ping) doPing();
643 | else {
644 | // more pings to do?
645 | pingProgress = 1;
646 | tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
647 | done();
648 | }
649 | }.bind(this);
650 | xhr[0].onerror = function() {
651 | // a ping failed, cancel test
652 | tverb("ping failed");
653 | if (settings.xhr_ignoreErrors === 0) {
654 | //abort
655 | pingStatus = "Fail";
656 | jitterStatus = "Fail";
657 | clearRequests();
658 | tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
659 | pingProgress = 1;
660 | done();
661 | }
662 | if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
663 | if (settings.xhr_ignoreErrors === 2) {
664 | //ignore failed ping
665 | i++;
666 | if (i < settings.count_ping) doPing();
667 | else {
668 | // more pings to do?
669 | pingProgress = 1;
670 | tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
671 | done();
672 | }
673 | }
674 | }.bind(this);
675 | // send xhr
676 | xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
677 | xhr[0].send();
678 | }.bind(this);
679 | doPing(); // start first ping
680 | }
681 | // telemetry
682 | function sendTelemetry(done) {
683 | if (settings.telemetry_level < 1) return;
684 | xhr = new XMLHttpRequest();
685 | xhr.onload = function() {
686 | try {
687 | var parts = xhr.responseText.split(" ");
688 | if (parts[0] == "id") {
689 | try {
690 | var id = parts[1];
691 | done(id);
692 | } catch (e) {
693 | done(null);
694 | }
695 | } else done(null);
696 | } catch (e) {
697 | done(null);
698 | }
699 | };
700 | xhr.onerror = function() {
701 | console.log("TELEMETRY ERROR " + xhr.status);
702 | done(null);
703 | };
704 | xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
705 | var telemetryIspInfo = {
706 | processedString: clientIp,
707 | rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
708 | };
709 | try {
710 | var fd = new FormData();
711 | fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
712 | fd.append("dl", dlStatus);
713 | fd.append("ul", ulStatus);
714 | fd.append("ping", pingStatus);
715 | fd.append("jitter", jitterStatus);
716 | fd.append("log", settings.telemetry_level > 1 ? log : "");
717 | fd.append("extra", settings.telemetry_extra);
718 | xhr.send(fd);
719 | } catch (ex) {
720 | var postData = "extra=" + encodeURIComponent(settings.telemetry_extra) + "&ispinfo=" + encodeURIComponent(JSON.stringify(telemetryIspInfo)) + "&dl=" + encodeURIComponent(dlStatus) + "&ul=" + encodeURIComponent(ulStatus) + "&ping=" + encodeURIComponent(pingStatus) + "&jitter=" + encodeURIComponent(jitterStatus) + "&log=" + encodeURIComponent(settings.telemetry_level > 1 ? log : "");
721 | xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
722 | xhr.send(postData);
723 | }
724 | }
725 |
--------------------------------------------------------------------------------