260 |
261 |
262 |
263 |
--------------------------------------------------------------------------------
/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/web.go:
--------------------------------------------------------------------------------
1 | package web
2 |
3 | import (
4 | "crypto/tls"
5 | "embed"
6 | "encoding/json"
7 | "io"
8 | "io/fs"
9 | "io/ioutil"
10 | "net"
11 | "net/http"
12 | "os"
13 | "regexp"
14 | "strconv"
15 | "strings"
16 |
17 | "github.com/coreos/go-systemd/activation"
18 | "github.com/go-chi/chi/v5"
19 | "github.com/go-chi/chi/v5/middleware"
20 | "github.com/go-chi/cors"
21 | "github.com/go-chi/render"
22 | "github.com/pires/go-proxyproto"
23 | log "github.com/sirupsen/logrus"
24 |
25 | "github.com/xiaoxinpro/speedtest-go-zh/config"
26 | "github.com/xiaoxinpro/speedtest-go-zh/results"
27 | )
28 |
29 | const (
30 | // chunk size is 1 mib
31 | chunkSize = 1048576
32 | )
33 |
34 | //go:embed assets
35 | var defaultAssets embed.FS
36 |
37 | var (
38 | // generate random data for download test on start to minimize runtime overhead
39 | randomData = getRandomData(chunkSize)
40 | )
41 |
42 | func ListenAndServe(conf *config.Config) error {
43 | r := chi.NewRouter()
44 | r.Use(middleware.RealIP)
45 | r.Use(middleware.GetHead)
46 |
47 | cs := cors.New(cors.Options{
48 | AllowedOrigins: []string{"*"},
49 | AllowedMethods: []string{"GET", "POST", "OPTIONS", "HEAD"},
50 | AllowedHeaders: []string{"*"},
51 | })
52 |
53 | r.Use(cs.Handler)
54 | r.Use(middleware.NoCache)
55 | r.Use(middleware.Recoverer)
56 |
57 | var assetFS http.FileSystem
58 | if fi, err := os.Stat(conf.AssetsPath); os.IsNotExist(err) || !fi.IsDir() {
59 | log.Warnf("Configured asset path %s does not exist or is not a directory, using default assets", conf.AssetsPath)
60 | sub, err := fs.Sub(defaultAssets, "assets")
61 | if err != nil {
62 | log.Fatalf("Failed when processing default assets: %s", err)
63 | }
64 | assetFS = http.FS(sub)
65 | } else {
66 | assetFS = justFilesFilesystem{fs: http.Dir(conf.AssetsPath), readDirBatchSize: 2}
67 | }
68 |
69 | r.Get("/*", pages(assetFS))
70 | r.HandleFunc("/empty", empty)
71 | r.HandleFunc("/backend/empty", empty)
72 | r.Get("/garbage", garbage)
73 | r.Get("/backend/garbage", garbage)
74 | r.Get("/getIP", getIP)
75 | r.Get("/backend/getIP", getIP)
76 | r.Get("/results", results.DrawPNG)
77 | r.Get("/results/", results.DrawPNG)
78 | r.Get("/backend/results", results.DrawPNG)
79 | r.Get("/backend/results/", results.DrawPNG)
80 | r.Post("/results/telemetry", results.Record)
81 | r.Post("/backend/results/telemetry", results.Record)
82 | r.HandleFunc("/stats", results.Stats)
83 | r.HandleFunc("/backend/stats", results.Stats)
84 |
85 | // PHP frontend default values compatibility
86 | r.HandleFunc("/empty.php", empty)
87 | r.HandleFunc("/backend/empty.php", empty)
88 | r.Get("/garbage.php", garbage)
89 | r.Get("/backend/garbage.php", garbage)
90 | r.Get("/getIP.php", getIP)
91 | r.Get("/backend/getIP.php", getIP)
92 | r.Post("/results/telemetry.php", results.Record)
93 | r.Post("/backend/results/telemetry.php", results.Record)
94 | r.HandleFunc("/stats.php", results.Stats)
95 | r.HandleFunc("/backend/stats.php", results.Stats)
96 |
97 | go listenProxyProtocol(conf, r)
98 |
99 | // See if systemd socket activation has been used when starting our process
100 | listeners, err := activation.Listeners()
101 | if err != nil {
102 | log.Fatalf("Error whilst checking for systemd socket activation %s", err)
103 | }
104 |
105 | var s error
106 |
107 | switch len(listeners) {
108 | case 0:
109 | addr := net.JoinHostPort(conf.BindAddress, conf.Port)
110 | log.Infof("Starting backend server on %s", addr)
111 |
112 | // TLS and HTTP/2.
113 | if conf.EnableTLS {
114 | log.Info("Use TLS connection.")
115 | if !(conf.EnableHTTP2) {
116 | srv := &http.Server{
117 | Addr: addr,
118 | Handler: r,
119 | TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
120 | }
121 | s = srv.ListenAndServeTLS(conf.TLSCertFile, conf.TLSKeyFile)
122 | } else {
123 | s = http.ListenAndServeTLS(addr, conf.TLSCertFile, conf.TLSKeyFile, r)
124 | }
125 | } else {
126 | if conf.EnableHTTP2 {
127 | log.Errorf("TLS is mandatory for HTTP/2. Ignore settings that enable HTTP/2.")
128 | }
129 | s = http.ListenAndServe(addr, r)
130 | }
131 | case 1:
132 | log.Info("Starting backend server on inherited file descriptor via systemd socket activation")
133 | if conf.BindAddress != "" || conf.Port != "" {
134 | log.Errorf("Both an address/port (%s:%s) has been specificed in the config AND externally configured socket activation has been detected", conf.BindAddress, conf.Port)
135 | log.Fatal(`Please deconfigure socket activation (e.g. in systemd unit files), or set both 'bind_address' and 'listen_port' to ''`)
136 | }
137 | s = http.Serve(listeners[0], r)
138 | default:
139 | log.Fatalf("Asked to listen on %s sockets via systemd activation. Sorry we currently only support listening on 1 socket.", len(listeners))
140 | }
141 | return s
142 | }
143 |
144 | func listenProxyProtocol(conf *config.Config, r *chi.Mux) {
145 | if conf.ProxyProtocolPort != "0" {
146 | addr := net.JoinHostPort(conf.BindAddress, conf.ProxyProtocolPort)
147 | l, err := net.Listen("tcp", addr)
148 | if err != nil {
149 | log.Fatalf("Cannot listen on proxy protocol port %s: %s", conf.ProxyProtocolPort, err)
150 | }
151 |
152 | pl := &proxyproto.Listener{Listener: l}
153 | defer pl.Close()
154 |
155 | log.Infof("Starting proxy protocol listener on %s", addr)
156 | log.Fatal(http.Serve(pl, r))
157 | }
158 | }
159 |
160 | func pages(fs http.FileSystem) http.HandlerFunc {
161 | fn := func(w http.ResponseWriter, r *http.Request) {
162 | if r.RequestURI == "/" {
163 | r.RequestURI = "/index.html"
164 | }
165 |
166 | http.FileServer(fs).ServeHTTP(w, r)
167 | }
168 |
169 | return fn
170 | }
171 |
172 | func empty(w http.ResponseWriter, r *http.Request) {
173 | _, err := io.Copy(ioutil.Discard, r.Body)
174 | if err != nil {
175 | w.WriteHeader(http.StatusBadRequest)
176 | return
177 | }
178 | _ = r.Body.Close()
179 |
180 | w.Header().Set("Connection", "keep-alive")
181 | w.WriteHeader(http.StatusOK)
182 | }
183 |
184 | func garbage(w http.ResponseWriter, r *http.Request) {
185 | w.Header().Set("Content-Description", "File Transfer")
186 | w.Header().Set("Content-Type", "application/octet-stream")
187 | w.Header().Set("Content-Disposition", "attachment; filename=random.dat")
188 | w.Header().Set("Content-Transfer-Encoding", "binary")
189 |
190 | // chunk size set to 4 by default
191 | chunks := 4
192 |
193 | ckSize := r.FormValue("ckSize")
194 | if ckSize != "" {
195 | i, err := strconv.ParseInt(ckSize, 10, 64)
196 | if err != nil {
197 | log.Errorf("Invalid chunk size: %s", ckSize)
198 | log.Warnf("Will use default value %d", chunks)
199 | } else {
200 | // limit max chunk size to 1024
201 | if i > 1024 {
202 | chunks = 1024
203 | } else {
204 | chunks = int(i)
205 | }
206 | }
207 | }
208 |
209 | for i := 0; i < chunks; i++ {
210 | if _, err := w.Write(randomData); err != nil {
211 | log.Errorf("Error writing back to client at chunk number %d: %s", i, err)
212 | break
213 | }
214 | }
215 | }
216 |
217 | func getIP(w http.ResponseWriter, r *http.Request) {
218 | var ret results.Result
219 |
220 | clientIP := r.RemoteAddr
221 | clientIP = strings.ReplaceAll(clientIP, "::ffff:", "")
222 |
223 | ip, _, err := net.SplitHostPort(r.RemoteAddr)
224 | if err == nil {
225 | clientIP = ip
226 | }
227 |
228 | isSpecialIP := true
229 | switch {
230 | case clientIP == "::1":
231 | ret.ProcessedString = clientIP + " - 本地 IPv6 地址"
232 | case strings.HasPrefix(clientIP, "fe80:"):
233 | ret.ProcessedString = clientIP + " - 本地子网 IPv6 地址"
234 | case strings.HasPrefix(clientIP, "127."):
235 | ret.ProcessedString = clientIP + " - 本地 IPv4 地址"
236 | case strings.HasPrefix(clientIP, "10."):
237 | ret.ProcessedString = clientIP + " - 局域网 IPv4 地址"
238 | case regexp.MustCompile(`^172\.(1[6-9]|2\d|3[01])\.`).MatchString(clientIP):
239 | ret.ProcessedString = clientIP + " - 局域网 IPv4 地址"
240 | case strings.HasPrefix(clientIP, "192.168"):
241 | ret.ProcessedString = clientIP + " - 局域网 IPv4 地址"
242 | case strings.HasPrefix(clientIP, "169.254"):
243 | ret.ProcessedString = clientIP + " - 本地子网 IPv4 地址"
244 | case regexp.MustCompile(`^100\.([6-9][0-9]|1[0-2][0-7])\.`).MatchString(clientIP):
245 | ret.ProcessedString = clientIP + " - CGNAT IPv4 地址"
246 | default:
247 | isSpecialIP = false
248 | }
249 |
250 | if isSpecialIP {
251 | b, _ := json.Marshal(&ret)
252 | if _, err := w.Write(b); err != nil {
253 | log.Errorf("Error writing to client: %s", err)
254 | }
255 | return
256 | }
257 |
258 | getISPInfo := r.FormValue("isp") == "true"
259 | distanceUnit := r.FormValue("distance")
260 |
261 | ret.ProcessedString = clientIP
262 |
263 | if getISPInfo {
264 | ispInfo := getIPInfo(clientIP)
265 | ret.RawISPInfo = ispInfo
266 |
267 | removeRegexp := regexp.MustCompile(`AS\d+\s`)
268 | isp := removeRegexp.ReplaceAllString(ispInfo.Organization, "")
269 |
270 | if isp == "" {
271 | isp = "Unknown ISP"
272 | }
273 |
274 | if ispInfo.Country != "" {
275 | isp += ", " + ispInfo.Country
276 | }
277 |
278 | if ispInfo.Location != "" {
279 | isp += " (" + calculateDistance(ispInfo.Location, distanceUnit) + ")"
280 | }
281 |
282 | ret.ProcessedString += " - " + isp
283 | }
284 |
285 | render.JSON(w, r, ret)
286 | }
287 |
--------------------------------------------------------------------------------
/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/xiaoxinpro/speedtest-go-zh/
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/xiaoxinpro/speedtest-go-zh"
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/xiaoxinpro/speedtest-go-zh/
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 |
--------------------------------------------------------------------------------