Removed everything

This commit is contained in:
dosse91 2021-03-25 20:49:54 +01:00
parent 1230058283
commit c2fa9dbd49
32 changed files with 2 additions and 13225 deletions

View file

@ -1,28 +0,0 @@
---
name: Bug report
about: Report a bug with this project. Don't use this if you need help configuring
it
---
## Description
A short description of what's going on
## Server
Every info you can provide about your server: web server, database, PHP version, ... as well as server-side speedtest settings
If possible, provide an URL to your speedtest so we can check it
## Client
Browser, OS, type of connection, unusual software, ...
## Steps to reproduce
* Do this
* Do that
* Bad stuff happens
## Expected behaviour
What should have happened
## Screenshots
If necessary, add screenshots of the test.
F12 > Network screenshots can be particularly useful

View file

@ -1,17 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
---
## Description
A short description of your idea
## Why it should be implemented
Who it would benefit, ...
## Optional: implementation suggestions
If you have experience in this field, feel free to give us suggestions
## Optional: screenshots
Add some screenshots, mockups, ... if they help clarify what you want

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

View file

@ -1,44 +0,0 @@
FROM php:7.4-apache
# Install extensions
RUN apt-get update && apt-get install -y \
libfreetype6-dev \
libjpeg62-turbo-dev \
libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv \
&& docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ \
&& docker-php-ext-install -j$(nproc) gd
# Prepare files and folders
RUN mkdir -p /speedtest/
# Copy sources
COPY backend/ /speedtest/backend
COPY results/*.php /speedtest/results/
COPY results/*.ttf /speedtest/results/
COPY *.js /speedtest/
COPY favicon.ico /speedtest/
COPY docker/servers.json /servers.json
COPY docker/*.php /speedtest/
COPY docker/entrypoint.sh /
# Prepare environment variabiles defaults
ENV TITLE=LibreSpeed
ENV MODE=standalone
ENV PASSWORD=password
ENV TELEMETRY=false
ENV ENABLE_ID_OBFUSCATION=false
ENV REDACT_IP_ADDRESSES=false
ENV WEBPORT=80
# Final touches
EXPOSE 80
CMD ["bash", "/entrypoint.sh"]

165
LICENSE
View file

@ -1,165 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View file

@ -1,30 +1,2 @@
![LibreSpeed Logo](https://github.com/librespeed/speedtest/blob/master/.logo/logo3.png?raw=true)
# LibreSpeed - Docker Version
This is the Docker version of LibreSpeed.
See the included `doc.md` or the wiki for instructions on how to use it.
## Go backend
A Go implementation is available in the [`speedtest-go`](https://github.com/librespeed/speedtest-go) repo, maintained by [Maddie Zhan](https://github.com/maddie).
## Donate
[![Donate with Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/fdossena/donate)
[Donate with PayPal](https://www.paypal.me/sineisochronic)
## License
Copyright (C) 2016-2021 Federico Dossena
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/lgpl>.
## LibreSpeed (docker branch)
The docker version has been merged into the master branch.

View file

@ -1,12 +0,0 @@
<?php
header( "HTTP/1.1 200 OK" );
if(isset($_GET["cors"])){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Encoding, Content-Type');
}
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: keep-alive");
?>

View file

@ -1,63 +0,0 @@
<?php
// Disable Compression
@ini_set('zlib.output_compression', 'Off');
@ini_set('output_buffering', 'Off');
@ini_set('output_handler', '');
/**
* @return int
*/
function getChunkCount()
{
if (
!array_key_exists('ckSize', $_GET)
|| !ctype_digit($_GET['ckSize'])
|| (int) $_GET['ckSize'] <= 0
) {
return 4;
}
if ((int) $_GET['ckSize'] > 1024) {
return 1024;
}
return (int) $_GET['ckSize'];
}
/**
* @return void
*/
function sendHeaders()
{
header('HTTP/1.1 200 OK');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
// Indicate a file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=random.dat');
header('Content-Transfer-Encoding: binary');
// Cache settings: never cache this request
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
// Determine how much data we should send
$chunks = getChunkCount();
// Generate data
$data = openssl_random_pseudo_bytes(1048576);
// Deliver chunks of 1048576 bytes
sendHeaders();
for ($i = 0; $i < $chunks; $i++) {
echo $data;
flush();
}

View file

@ -1,346 +0,0 @@
<?php
/*
* This script detects the client's IP address and fetches ISP info from ipinfo.io/
* Output from this script is a JSON string composed of 2 objects: a string called processedString which contains the combined IP, ISP, Contry and distance as it can be presented to the user; and an object called rawIspInfo which contains the raw data from ipinfo.io (will be empty if isp detection is disabled).
* Client side, the output of this script can be treated as JSON or as regular text. If the output is regular text, it will be shown to the user as is.
*/
error_reporting(0);
define('API_KEY_FILE', 'getIP_ipInfo_apikey.php');
define('SERVER_LOCATION_CACHE_FILE', 'getIP_serverLocation.php');
/**
* @return string
*/
function getClientIp()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
$ip = $_SERVER['HTTP_X_REAL_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = preg_replace('/,.*/', '', $ip); # hosts are comma-separated, client is first
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return preg_replace('/^::ffff:/', '', $ip);
}
/**
* @param string $ip
*
* @return string|null
*/
function getLocalOrPrivateIpInfo($ip)
{
// ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
if ('::1' === $ip) {
return 'localhost IPv6 access';
}
// simplified IPv6 link-local address (should match fe80::/10)
if (stripos($ip, 'fe80:') === 0) {
return 'link-local IPv6 access';
}
// anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
if (strpos($ip, '127.') === 0) {
return 'localhost IPv4 access';
}
// 10/8 private IPv4
if (strpos($ip, '10.') === 0) {
return 'private IPv4 access';
}
// 172.16/12 private IPv4
if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) {
return 'private IPv4 access';
}
// 192.168/16 private IPv4
if (strpos($ip, '192.168.') === 0) {
return 'private IPv4 access';
}
// IPv4 link-local
if (strpos($ip, '169.254.') === 0) {
return 'link-local IPv4 access';
}
return null;
}
/**
* @return string
*/
function getIpInfoTokenString()
{
if (
!file_exists(API_KEY_FILE)
|| !is_readable(API_KEY_FILE)
) {
return '';
}
require API_KEY_FILE;
if (empty($IPINFO_APIKEY)) {
return '';
}
return '?token='.$IPINFO_APIKEY;
}
/**
* @param string $ip
*
* @return array|null
*/
function getIspInfo($ip)
{
$json = file_get_contents('https://ipinfo.io/'.$ip.'/json'.getIpInfoTokenString());
if (!is_string($json)) {
return null;
}
$data = json_decode($json, true);
if (!is_array($data)) {
return null;
}
return $data;
}
/**
* @param array|null $rawIspInfo
*
* @return string
*/
function getIsp($rawIspInfo)
{
if (
!is_array($rawIspInfo)
|| !array_key_exists('org', $rawIspInfo)
|| !is_string($rawIspInfo['org'])
|| empty($rawIspInfo['org'])
) {
return 'Unknown ISP';
}
// Remove AS##### from ISP name, if present
return preg_replace('/AS\\d+\\s/', '', $rawIspInfo['org']);
}
/**
* @return string|null
*/
function getServerLocation()
{
$serverLoc = null;
if (
file_exists(SERVER_LOCATION_CACHE_FILE)
&& is_readable(SERVER_LOCATION_CACHE_FILE)
) {
require SERVER_LOCATION_CACHE_FILE;
}
if (is_string($serverLoc) && !empty($serverLoc)) {
return $serverLoc;
}
$json = file_get_contents('https://ipinfo.io/json'.getIpInfoTokenString());
if (!is_string($json)) {
return null;
}
$details = json_decode($json, true);
if (
!is_array($details)
|| !array_key_exists('loc', $details)
|| !is_string($details['loc'])
|| empty($details['loc'])
) {
return null;
}
$serverLoc = $details['loc'];
$cacheData = "<?php\n\n\$serverLoc = '".addslashes($serverLoc)."';\n";
file_put_contents(SERVER_LOCATION_CACHE_FILE, $cacheData);
return $serverLoc;
}
/**
* Optimized algorithm from http://www.codexworld.com
*
* @param float $latitudeFrom
* @param float $longitudeFrom
* @param float $latitudeTo
* @param float $longitudeTo
*
* @return float [km]
*/
function distance(
$latitudeFrom,
$longitudeFrom,
$latitudeTo,
$longitudeTo
) {
$rad = M_PI / 180;
$theta = $longitudeFrom - $longitudeTo;
$dist = sin($latitudeFrom * $rad)
* sin($latitudeTo * $rad)
+ cos($latitudeFrom * $rad)
* cos($latitudeTo * $rad)
* cos($theta * $rad);
return acos($dist) / $rad * 60 * 1.853;
}
/**
* @param array|null $rawIspInfo
*
* @return string|null
*/
function getDistance($rawIspInfo)
{
if (
!is_array($rawIspInfo)
|| !array_key_exists('loc', $rawIspInfo)
|| !isset($_GET['distance'])
|| !in_array($_GET['distance'], ['mi', 'km'], true)
) {
return null;
}
$unit = $_GET['distance'];
$clientLocation = $rawIspInfo['loc'];
$serverLocation = getServerLocation();
if (!is_string($serverLocation)) {
return null;
}
return calculateDistance(
$serverLocation,
$clientLocation,
$unit
);
}
/**
* @param string $clientLocation
* @param string $serverLocation
* @param string $unit
*
* @return string
*/
function calculateDistance($clientLocation, $serverLocation, $unit)
{
list($clientLatitude, $clientLongitude) = explode(',', $clientLocation);
list($serverLatitude, $serverLongitude) = explode(',', $serverLocation);
$dist = distance(
$clientLatitude,
$clientLongitude,
$serverLatitude,
$serverLongitude
);
if ('mi' === $unit) {
$dist /= 1.609344;
$dist = round($dist, -1);
if ($dist < 15) {
$dist = '<15';
}
return $dist.' mi';
}
if ('km' === $unit) {
$dist = round($dist, -1);
if ($dist < 20) {
$dist = '<20';
}
return $dist.' km';
}
return null;
}
/**
* @return void
*/
function sendHeaders()
{
header('Content-Type: application/json; charset=utf-8');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
/**
* @param string $ip
* @param string|null $ipInfo
* @param string|null $distance
* @param array|null $rawIspInfo
*
* @return void
*/
function sendResponse(
$ip,
$ipInfo = null,
$distance = null,
$rawIspInfo = null
) {
$processedString = $ip;
if (is_string($ipInfo)) {
$processedString .= ' - '.$ipInfo;
}
if (
is_array($rawIspInfo)
&& array_key_exists('country', $rawIspInfo)
) {
$processedString .= ', '.$rawIspInfo['country'];
}
if (is_string($distance)) {
$processedString .= ' ('.$distance.')';
}
sendHeaders();
echo json_encode([
'processedString' => $processedString,
'rawIspInfo' => $rawIspInfo ?: '',
]);
}
$ip = getClientIp();
$localIpInfo = getLocalOrPrivateIpInfo($ip);
// local ip, no need to fetch further information
if (is_string($localIpInfo)) {
sendResponse($ip, $localIpInfo);
exit;
}
if (!isset($_GET['isp'])) {
sendResponse($ip);
exit;
}
$rawIspInfo = getIspInfo($ip);
$isp = getIsp($rawIspInfo);
$distance = getDistance($rawIspInfo);
sendResponse($ip, $isp, $distance, $rawIspInfo);

View file

@ -1,4 +0,0 @@
<?php
// put your token between the quotes if you have one
$IPINFO_APIKEY = '';

106
doc.md
View file

@ -1,106 +0,0 @@
A docker version of LibreSpeed is available on docker hub: [https://hub.docker.com/r/adolfintel/speedtest/](https://hub.docker.com/r/adolfintel/speedtest/)
## Downloading from Docker hub
To download LibreSpeed from the docker hub, use this command:
```
docker pull adolfintel/speedtest
```
You will now have a new docker image called `adolfintel/speedtest`.
## Standalone mode
If you want to install LibreSpeed on a single server, you need to configure it in standalone mode. To do this, set the `MODE` environment variable to `standalone`.
The test can be accessed on port 80.
Here's a list of additional environment variables available in this mode:
* __`TITLE`__: Title of your speedtest. Default value: `LibreSpeed`
* __`TELEMETRY`__: Whether to enable telemetry or not. Default value: `false`
* __`ENABLE_ID_OBFUSCATION`__: When set to true with telemetry enabled, test IDs are obfuscated, to avoid exposing the database internal sequential IDs. Default value: `false`
* __`REDACT_IP_ADDRESSES`__: When set to true with telemetry enabled, IP addresses and hostnames are redacted from the collected telemetry, for better privacy. Default value: `false`
* __`PASSWORD`__: Password to access the stats page. If not set, stats page will not allow accesses.
* __`EMAIL`__: Email address for GDPR requests. Must be specified when telemetry is enabled.
* __`IPINFO_APIKEY`__: API key for ipinfo.io. Optional, but required if you expect to serve a large number of tests
* __`DISABLE_IPINFO`__: If set to true, ISP info and distance will not be fetched from ipinfo.io. Default: value: `false`
* __`DISTANCE`__: When `DISABLE_IPINFO` is set to false, this specifies how the distance from the server is measured. Can be either `km` for kilometers, `mi` for miles, or an empty string to disable distance measurement. Default value: `km`
* __`WEBPORT`__: Allows choosing a custom port for the included web server. Default value: `80`. Note that you will have to expose it through docker with the -p argument
If telemetry is enabled, a stats page will be available at `http://your.server/results/stats.php`, but a password must be specified.
###### Example
This command starts LibreSpeed in standalone mode, with the default settings, on port 80:
```
docker run -e MODE=standalone -p 80:80 -it adolfintel/speedtest
```
This command starts LibreSpeed in standalone mode, with telemetry, ID obfuscation and a stats password, on port 86:
```
docker run -e MODE=standalone -e TELEMETRY=true -e ENABLE_ID_OBFUSCATION=true -e PASSWORD="yourPasswordHere" -e WEBPORT=86 -p 86:86 -it adolfintel/speedtest
```
## Multiple Points of Test
For multiple servers, you need to set up 1+ LibreSpeed backends, and 1 LibreSpeed frontend.
### Backend mode
In backend mode, LibreSpeed provides only a test point with no UI. To do this, set the `MODE` environment variable to `backend`.
The following backend files can be accessed on port 80: `garbage.php`, `empty.php`, `getIP.php`
Here's a list of additional environment variables available in this mode:
* __`IPINFO_APIKEY`__: API key for ipinfo.io. Optional, but required if you expect to serve a large number of tests
###### Example:
This command starts LibreSpeed in backend mode, with the default settings, on port 80:
```
docker run -e MODE=backend -p 80:80 -it adolfintel/speedtest
```
### Frontend mode
In frontend mode, LibreSpeed serves clients the Web UI and a list of servers. To do this:
* Set the `MODE` environment variable to `frontend`
* Create a servers.json file with your test points. The syntax is the following:
```
[
{
"name": "Friendly name for Server 1",
"server" :"//server1.mydomain.com/",
"dlURL" :"garbage.php",
"ulURL" :"empty.php",
"pingURL" :"empty.php",
"getIpURL" :"getIP.php"
},
{
"name": "Friendly name for Server 2",
"server" :"https://server2.mydomain.com/",
"dlURL" :"garbage.php",
"ulURL" :"empty.php",
"pingURL" :"empty.php",
"getIpURL" :"getIP.php"
},
...more servers...
]
```
Note: if a server only supports HTTP or HTTPS, specify the protocol in the server field. If it supports both, just use `//`.
* Mount this file to `/servers.json` in the container (example at the end of this file)
The test can be accessed on port 80.
Here's a list of additional environment variables available in this mode:
* __`TITLE`__: Title of your speedtest. Default value: `LibreSpeed`
* __`TELEMETRY`__: Whether to enable telemetry or not. Default value: `false`
* __`ENABLE_ID_OBFUSCATION`__: When set to true with telemetry enabled, test IDs are obfuscated, to avoid exposing the database internal sequential IDs. Default value: `false`
* __`REDACT_IP_ADDRESSES`__: When set to true with telemetry enabled, IP addresses and hostnames are redacted from the collected telemetry, for better privacy. Default value: `false`
* __`PASSWORD`__: Password to access the stats page. If not set, stats page will not allow accesses.
* __`EMAIL`__: Email address for GDPR requests. Must be specified when telemetry is enabled.
* __`DISABLE_IPINFO`__: If set to true, ISP info and distance will not be fetched from ipinfo.io. Default: value: `false`
* __`DISTANCE`__: When `DISABLE_IPINFO` is set to false, this specifies how the distance from the server is measured. Can be either `km` for kilometers, `mi` for miles, or an empty string to disable distance measurement. Default value: `km`
* __`WEBPORT`__: Allows choosing a custom port for the included web server. Default value: `80`
###### Example
This command starts LibreSpeed in frontend mode, with a given `servers.json` file, and with telemetry, ID obfuscation, and a stats password:
```
docker run -e MODE=frontend -e TELEMETRY=true -e ENABLE_ID_OBFUSCATION=true -e PASSWORD="yourPasswordHere" -v $(pwd)/servers.json:/servers.json -p 80:80 -it adolfintel/speedtest
```

View file

@ -1,68 +0,0 @@
#!/bin/bash
set -e
set -x
# Cleanup
rm -rf /var/www/html/*
# Copy frontend files
cp /speedtest/*.js /var/www/html/
# Copy favicon
cp /speedtest/favicon.ico /var/www/html/
# Set up backend side for standlone modes
if [ "$MODE" == "standalone" ]; then
cp -r /speedtest/backend/ /var/www/html/backend
if [ ! -z "$IPINFO_APIKEY" ]; then
sed -i s/\$IPINFO_APIKEY\ =\ \'\'/\$IPINFO_APIKEY\ =\ \'$IPINFO_APIKEY\'/g /var/www/html/backend/getIP_ipInfo_apikey.php
fi
fi
if [ "$MODE" == "backend" ]; then
cp -r /speedtest/backend/* /var/www/html
if [ ! -z "$IPINFO_APIKEY" ]; then
sed -i s/\$IPINFO_APIKEY\ =\ \'\'/\$IPINFO_APIKEY\ =\ \'$IPINFO_APIKEY\'/g /var/www/html/getIP_ipInfo_apikey.php
fi
fi
# Set up index.php for frontend-only or standalone modes
if [ "$MODE" == "frontend" ]; then
cp /speedtest/frontend.php /var/www/html/index.php
elif [ "$MODE" == "standalone" ]; then
cp /speedtest/standalone.php /var/www/html/index.php
fi
# Apply Telemetry settings when running in standalone or frontend mode and telemetry is enabled
if [[ "$TELEMETRY" == "true" && ( "$MODE" == "frontend" || "$MODE" == "standalone" ) ]]; then
cp -r /speedtest/results /var/www/html/results
sed -i s/\$db_type\ =\ \'.*\'/\$db_type\ =\ \'sqlite\'\/g /var/www/html/results/telemetry_settings.php
sed -i s/\$Sqlite_db_file\ =\ \'.*\'/\$Sqlite_db_file=\'\\\/database\\\/db.sql\'/g /var/www/html/results/telemetry_settings.php
sed -i s/\$stats_password\ =\ \'.*\'/\$stats_password\ =\ \'$PASSWORD\'/g /var/www/html/results/telemetry_settings.php
if [ "$ENABLE_ID_OBFUSCATION" == "true" ]; then
sed -i s/\$enable_id_obfuscation\ =\ .*\;/\$enable_id_obfuscation\ =\ true\;/g /var/www/html/results/telemetry_settings.php
fi
if [ "$REDACT_IP_ADDRESSES" == "true" ]; then
sed -i s/\$redact_ip_addresses\ =\ .*\;/\$redact_ip_addresses\ =\ true\;/g /var/www/html/results/telemetry_settings.php
fi
mkdir -p /database/
chown www-data /database/
fi
chown -R www-data /var/www/html/*
# Allow selection of Apache port for network_mode: host
if [ "$WEBPORT" != "80" ]; then
sed -i "s/^Listen 80\$/Listen $WEBPORT/g" /etc/apache2/ports.conf
sed -i "s/*:80>/*:$WEBPORT>/g" /etc/apache2/sites-available/000-default.conf
fi
echo "Done, Starting APACHE"
# This runs apache
apache2-foreground

View file

@ -1,472 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no" />
<meta charset="UTF-8" />
<script type="text/javascript" src="speedtest.js"></script>
<script type="text/javascript">
function I(i){return document.getElementById(i);}
//LIST OF TEST SERVERS. See documentation for details if needed
var SPEEDTEST_SERVERS= <?= file_get_contents('/servers.json') ?: '[]' ?>;
//INITIALIZE SPEEDTEST
var s=new Speedtest(); //create speedtest object
<?php if(getenv("TELEMETRY")=="true"){ ?>
s.setParameter("telemetry_level","basic");
<?php } ?>
<?php if(getenv("DISABLE_IPINFO")=="true"){ ?>
s.setParameter("getIp_ispInfo","false");
<?php } ?>
<?php if(getenv("DISTANCE")){ ?>
s.setParameter("getIp_ispInfo_distance","<?=getenv("DISTANCE") ?>");
<?php } ?>
//SERVER AUTO SELECTION
function initServers(){
var noServersAvailable=function(){
I("message").innerHTML="No servers available";
}
var runServerSelect=function(){
s.selectServer(function(server){
if(server!=null){ //at least 1 server is available
I("loading").className="hidden"; //hide loading message
//populate server list for manual selection
for(var i=0;i<SPEEDTEST_SERVERS.length;i++){
if(SPEEDTEST_SERVERS[i].pingT==-1) continue;
var option=document.createElement("option");
option.value=i;
option.textContent=SPEEDTEST_SERVERS[i].name;
if(SPEEDTEST_SERVERS[i]===server) option.selected=true;
I("server").appendChild(option);
}
//show test UI
I("testWrapper").className="visible";
initUI();
}else{ //no servers are available, the test cannot proceed
noServersAvailable();
}
});
}
if(typeof SPEEDTEST_SERVERS === "string"){
//need to fetch list of servers from specified URL
s.loadServerList(SPEEDTEST_SERVERS,function(servers){
if(servers==null){ //failed to load server list
noServersAvailable();
}else{ //server list loaded
SPEEDTEST_SERVERS=servers;
runServerSelect();
}
});
}else{
//hardcoded server list
s.addTestPoints(SPEEDTEST_SERVERS);
runServerSelect();
}
}
var meterBk=/Trident.*rv:(\d+\.\d+)/i.test(navigator.userAgent)?"#EAEAEA":"#80808040";
var dlColor="#6060AA",
ulColor="#616161";
var progColor=meterBk;
//CODE FOR GAUGES
function drawMeter(c,amount,bk,fg,progress,prog){
var ctx=c.getContext("2d");
var dp=window.devicePixelRatio||1;
var cw=c.clientWidth*dp, ch=c.clientHeight*dp;
var sizScale=ch*0.0055;
if(c.width==cw&&c.height==ch){
ctx.clearRect(0,0,cw,ch);
}else{
c.width=cw;
c.height=ch;
}
ctx.beginPath();
ctx.strokeStyle=bk;
ctx.lineWidth=12*sizScale;
ctx.arc(c.width/2,c.height-58*sizScale,c.height/1.8-ctx.lineWidth,-Math.PI*1.1,Math.PI*0.1);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle=fg;
ctx.lineWidth=12*sizScale;
ctx.arc(c.width/2,c.height-58*sizScale,c.height/1.8-ctx.lineWidth,-Math.PI*1.1,amount*Math.PI*1.2-Math.PI*1.1);
ctx.stroke();
if(typeof progress !== "undefined"){
ctx.fillStyle=prog;
ctx.fillRect(c.width*0.3,c.height-16*sizScale,c.width*0.4*progress,4*sizScale);
}
}
function mbpsToAmount(s){
return 1-(1/(Math.pow(1.3,Math.sqrt(s))));
}
function format(d){
d=Number(d);
if(d<10) return d.toFixed(2);
if(d<100) return d.toFixed(1);
return d.toFixed(0);
}
//UI CODE
var uiData=null;
function startStop(){
if(s.getState()==3){
//speedtest is running, abort
s.abort();
data=null;
I("startStopBtn").className="";
I("server").disabled=false;
initUI();
}else{
//test is not running, begin
I("startStopBtn").className="running";
I("shareArea").style.display="none";
I("server").disabled=true;
s.onupdate=function(data){
uiData=data;
};
s.onend=function(aborted){
I("startStopBtn").className="";
I("server").disabled=false;
updateUI(true);
if(!aborted){
//if testId is present, show sharing panel, otherwise do nothing
try{
var testId=uiData.testId;
if(testId!=null){
var shareURL=window.location.href.substring(0,window.location.href.lastIndexOf("/"))+"/results/?id="+testId;
I("resultsImg").src=shareURL;
I("resultsURL").value=shareURL;
I("testId").innerHTML=testId;
I("shareArea").style.display="";
}
}catch(e){}
}
};
s.start();
}
}
//this function reads the data sent back by the test and updates the UI
function updateUI(forced){
if(!forced&&s.getState()!=3) return;
if(uiData==null) return;
var status=uiData.testState;
I("ip").textContent=uiData.clientIp;
I("dlText").textContent=(status==1&&uiData.dlStatus==0)?"...":format(uiData.dlStatus);
drawMeter(I("dlMeter"),mbpsToAmount(Number(uiData.dlStatus*(status==1?oscillate():1))),meterBk,dlColor,Number(uiData.dlProgress),progColor);
I("ulText").textContent=(status==3&&uiData.ulStatus==0)?"...":format(uiData.ulStatus);
drawMeter(I("ulMeter"),mbpsToAmount(Number(uiData.ulStatus*(status==3?oscillate():1))),meterBk,ulColor,Number(uiData.ulProgress),progColor);
I("pingText").textContent=format(uiData.pingStatus);
I("jitText").textContent=format(uiData.jitterStatus);
}
function oscillate(){
return 1+0.02*Math.sin(Date.now()/100);
}
//update the UI every frame
window.requestAnimationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||(function(callback,element){setTimeout(callback,1000/60);});
function frame(){
requestAnimationFrame(frame);
updateUI();
}
frame(); //start frame loop
//function to (re)initialize UI
function initUI(){
drawMeter(I("dlMeter"),0,meterBk,dlColor,0);
drawMeter(I("ulMeter"),0,meterBk,ulColor,0);
I("dlText").textContent="";
I("ulText").textContent="";
I("pingText").textContent="";
I("jitText").textContent="";
I("ip").textContent="";
}
</script>
<style type="text/css">
html,body{
border:none; padding:0; margin:0;
background:#FFFFFF;
color:#202020;
}
body{
text-align:center;
font-family:"Roboto",sans-serif;
}
h1{
color:#404040;
}
#loading{
background-color:#FFFFFF;
color:#404040;
text-align:center;
}
span.loadCircle{
display:inline-block;
width:2em;
height:2em;
vertical-align:middle;
background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAP1BMVEUAAAB2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZyFzwnAAAAFHRSTlMAEvRFvX406baecwbf0casimhSHyiwmqgAAADpSURBVHja7dbJbQMxAENRahnN5lkc//5rDRAkDeRgHszXgACJoKiIiIiIiIiIiIiIiIiIiIj4HHspsrpAVhdVVguzrA4OWc10WcEqpwKbnBo0OU1Q5NSpsoJFTgOecrrdEag85DRgktNqfoEdTjnd7hrEHMEJvmRUYJbTYk5Agy6nau6Abp5Cm7mDBtRdPi9gyKdU7w4p1fsLvyqs8hl4z9/w3n/Hmr9WoQ65lAU4d7lMYOz//QboRR5jBZibLMZdAR6O/Vfa1PlxNr3XdS3HzK/HVPRu/KnLs8iAOh993VpRRERERMT/fAN60wwWaVyWwAAAAABJRU5ErkJggg==');
background-size:2em 2em;
margin-right:0.5em;
animation: spin 0.6s linear infinite;
}
@keyframes spin{
0%{transform:rotate(0deg);}
100%{transform:rotate(359deg);}
}
#startStopBtn{
display:inline-block;
margin:0 auto;
color:#6060AA;
background-color:rgba(0,0,0,0);
border:0.15em solid #6060FF;
border-radius:0.3em;
transition:all 0.3s;
box-sizing:border-box;
width:8em; height:3em;
line-height:2.7em;
cursor:pointer;
box-shadow: 0 0 0 rgba(0,0,0,0.1), inset 0 0 0 rgba(0,0,0,0.1);
}
#startStopBtn:hover{
box-shadow: 0 0 2em rgba(0,0,0,0.1), inset 0 0 1em rgba(0,0,0,0.1);
}
#startStopBtn.running{
background-color:#FF3030;
border-color:#FF6060;
color:#FFFFFF;
}
#startStopBtn:before{
content:"Start";
}
#startStopBtn.running:before{
content:"Abort";
}
#serverArea{
margin-top:1em;
}
#server{
font-size:1em;
padding:0.2em;
}
#test{
margin-top:2em;
margin-bottom:12em;
}
div.testArea{
display:inline-block;
width:16em;
height:12.5em;
position:relative;
box-sizing:border-box;
}
div.testArea2{
display:inline-block;
width:14em;
height:7em;
position:relative;
box-sizing:border-box;
text-align:center;
}
div.testArea div.testName{
position:absolute;
top:0.1em; left:0;
width:100%;
font-size:1.4em;
z-index:9;
}
div.testArea2 div.testName{
display:block;
text-align:center;
font-size:1.4em;
}
div.testArea div.meterText{
position:absolute;
bottom:1.55em; left:0;
width:100%;
font-size:2.5em;
z-index:9;
}
div.testArea2 div.meterText{
display:inline-block;
font-size:2.5em;
}
div.meterText:empty:before{
content:"0.00";
}
div.testArea div.unit{
position:absolute;
bottom:2em; left:0;
width:100%;
z-index:9;
}
div.testArea2 div.unit{
display:inline-block;
}
div.testArea canvas{
position:absolute;
top:0; left:0; width:100%; height:100%;
z-index:1;
}
div.testGroup{
display:block;
margin: 0 auto;
}
#shareArea{
width:95%;
max-width:40em;
margin:0 auto;
margin-top:2em;
}
#shareArea > *{
display:block;
width:100%;
height:auto;
margin: 0.25em 0;
}
#privacyPolicy{
position:fixed;
top:2em;
bottom:2em;
left:2em;
right:2em;
overflow-y:auto;
width:auto;
height:auto;
box-shadow:0 0 3em 1em #000000;
z-index:999999;
text-align:left;
background-color:#FFFFFF;
padding:1em;
}
a.privacy{
text-align:center;
font-size:0.8em;
color:#808080;
display:block;
}
@media all and (max-width:40em){
body{
font-size:0.8em;
}
}
div.visible{
animation: fadeIn 0.4s;
display:block;
}
div.hidden{
animation: fadeOut 0.4s;
display:none;
}
@keyframes fadeIn{
0%{
opacity:0;
}
100%{
opacity:1;
}
}
@keyframes fadeOut{
0%{
display:block;
opacity:1;
}
100%{
display:block;
opacity:0;
}
}
</style>
<title><?= getenv('TITLE') ?: 'LibreSpeed Example' ?></title>
</head>
<body onload="initServers()">
<h1><?= getenv('TITLE') ?: 'LibreSpeed Example' ?></h1>
<div id="loading" class="visible">
<p id="message"><span class="loadCircle"></span>Selecting a server...</p>
</div>
<div id="testWrapper" class="hidden">
<div id="startStopBtn" onclick="startStop()"></div>
<?php if(getenv("TELEMETRY")=="true"){ ?>
<a class="privacy" href="#" onclick="I('privacyPolicy').style.display=''">Privacy</a>
<?php } ?>
<div id="serverArea">
Server: <select id="server" onchange="s.setSelectedServer(SPEEDTEST_SERVERS[this.value])"></select>
</div>
<div id="test">
<div class="testGroup">
<div class="testArea2">
<div class="testName">Ping</div>
<div id="pingText" class="meterText" style="color:#AA6060"></div>
<div class="unit">ms</div>
</div>
<div class="testArea2">
<div class="testName">Jitter</div>
<div id="jitText" class="meterText" style="color:#AA6060"></div>
<div class="unit">ms</div>
</div>
</div>
<div class="testGroup">
<div class="testArea">
<div class="testName">Download</div>
<canvas id="dlMeter" class="meter"></canvas>
<div id="dlText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
<div class="testArea">
<div class="testName">Upload</div>
<canvas id="ulMeter" class="meter"></canvas>
<div id="ulText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
</div>
<div id="ipArea">
<span id="ip"></span>
</div>
<div id="shareArea" style="display:none">
<h3>Share results</h3>
<p>Test ID: <span id="testId"></span></p>
<input type="text" value="" id="resultsURL" readonly="readonly" onclick="this.select();this.focus();this.select();document.execCommand('copy');alert('Link copied')"/>
<img src="" id="resultsImg" />
</div>
</div>
<a href="https://github.com/librespeed/speedtest">Source code</a>
</div>
<div id="privacyPolicy" style="display:none">
<h2>Privacy Policy</h2>
<p>This HTML5 Speedtest server is configured with telemetry enabled.</p>
<h4>What data we collect</h4>
<p>
At the end of the test, the following data is collected and stored:
<ul>
<li>Test ID</li>
<li>Time of testing</li>
<li>Test results (download and upload speed, ping and jitter)</li>
<li>IP address</li>
<li>ISP information</li>
<li>Approximate location (inferred from IP address, not GPS)</li>
<li>User agent and browser locale</li>
<li>Test log (contains no personal information)</li>
</ul>
</p>
<h4>How we use the data</h4>
<p>
Data collected through this service is used to:
<ul>
<li>Allow sharing of test results (sharable image for forums, etc.)</li>
<li>To improve the service offered to you (for instance, to detect problems on our side)</li>
</ul>
No personal information is disclosed to third parties.
</p>
<h4>Your consent</h4>
<p>
By starting the test, you consent to the terms of this privacy policy.
</p>
<h4>Data removal</h4>
<p>
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.<br/><br/>
Contact this email address for all deletion requests: <a href="mailto:<?=getenv("EMAIL") ?>"><?=getenv("EMAIL") ?></a>.
</p>
<br/><br/>
<a class="privacy" href="#" onclick="I('privacyPolicy').style.display='none'">Close</a><br/>
</div>
</body>
</html>

View file

@ -1,19 +0,0 @@
[
{
"name": "Speedtest Demo Server (Helsinki)",
"server" :"//fi.openspeed.org/",
"dlURL" :"garbage.php",
"ulURL" :"empty.php",
"pingURL" :"empty.php",
"getIpURL" :"getIP.php"
},
{
"name": "Old Speedtest Demo Server",
"server": "//mpotdemo.fdossena.com/",
"dlURL": "garbage.php",
"ulURL": "empty.php",
"pingURL": "empty.php",
"getIpURL": "getIP.php"
}
]

View file

@ -1,365 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no" />
<meta charset="UTF-8" />
<link rel="shortcut icon" href="favicon.ico">
<script type="text/javascript" src="speedtest.js"></script>
<script type="text/javascript">
function I(i){return document.getElementById(i);}
//INITIALIZE SPEEDTEST
var s=new Speedtest(); //create speedtest object
<?php if(getenv("TELEMETRY")=="true"){ ?>
s.setParameter("telemetry_level","basic");
<?php } ?>
<?php if(getenv("DISABLE_IPINFO")=="true"){ ?>
s.setParameter("getIp_ispInfo",false);
<?php } ?>
<?php if(getenv("DISTANCE")){ ?>
s.setParameter("getIp_ispInfo_distance","<?=getenv("DISTANCE") ?>");
<?php } ?>
var meterBk=/Trident.*rv:(\d+\.\d+)/i.test(navigator.userAgent)?"#EAEAEA":"#80808040";
var dlColor="#6060AA",
ulColor="#616161";
var progColor=meterBk;
//CODE FOR GAUGES
function drawMeter(c,amount,bk,fg,progress,prog){
var ctx=c.getContext("2d");
var dp=window.devicePixelRatio||1;
var cw=c.clientWidth*dp, ch=c.clientHeight*dp;
var sizScale=ch*0.0055;
if(c.width==cw&&c.height==ch){
ctx.clearRect(0,0,cw,ch);
}else{
c.width=cw;
c.height=ch;
}
ctx.beginPath();
ctx.strokeStyle=bk;
ctx.lineWidth=12*sizScale;
ctx.arc(c.width/2,c.height-58*sizScale,c.height/1.8-ctx.lineWidth,-Math.PI*1.1,Math.PI*0.1);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle=fg;
ctx.lineWidth=12*sizScale;
ctx.arc(c.width/2,c.height-58*sizScale,c.height/1.8-ctx.lineWidth,-Math.PI*1.1,amount*Math.PI*1.2-Math.PI*1.1);
ctx.stroke();
if(typeof progress !== "undefined"){
ctx.fillStyle=prog;
ctx.fillRect(c.width*0.3,c.height-16*sizScale,c.width*0.4*progress,4*sizScale);
}
}
function mbpsToAmount(s){
return 1-(1/(Math.pow(1.3,Math.sqrt(s))));
}
function format(d){
d=Number(d);
if(d<10) return d.toFixed(2);
if(d<100) return d.toFixed(1);
return d.toFixed(0);
}
//UI CODE
var uiData=null;
function startStop(){
if(s.getState()==3){
//speedtest is running, abort
s.abort();
data=null;
I("startStopBtn").className="";
initUI();
}else{
//test is not running, begin
I("startStopBtn").className="running";
I("shareArea").style.display="none";
s.onupdate=function(data){
uiData=data;
};
s.onend=function(aborted){
I("startStopBtn").className="";
updateUI(true);
if(!aborted){
//if testId is present, show sharing panel, otherwise do nothing
try{
var testId=uiData.testId;
if(testId!=null){
var shareURL=window.location.href.substring(0,window.location.href.lastIndexOf("/"))+"/results/?id="+testId;
I("resultsImg").src=shareURL;
I("resultsURL").value=shareURL;
I("testId").innerHTML=testId;
I("shareArea").style.display="";
}
}catch(e){}
}
};
s.start();
}
}
//this function reads the data sent back by the test and updates the UI
function updateUI(forced){
if(!forced&&s.getState()!=3) return;
if(uiData==null) return;
var status=uiData.testState;
I("ip").textContent=uiData.clientIp;
I("dlText").textContent=(status==1&&uiData.dlStatus==0)?"...":format(uiData.dlStatus);
drawMeter(I("dlMeter"),mbpsToAmount(Number(uiData.dlStatus*(status==1?oscillate():1))),meterBk,dlColor,Number(uiData.dlProgress),progColor);
I("ulText").textContent=(status==3&&uiData.ulStatus==0)?"...":format(uiData.ulStatus);
drawMeter(I("ulMeter"),mbpsToAmount(Number(uiData.ulStatus*(status==3?oscillate():1))),meterBk,ulColor,Number(uiData.ulProgress),progColor);
I("pingText").textContent=format(uiData.pingStatus);
I("jitText").textContent=format(uiData.jitterStatus);
}
function oscillate(){
return 1+0.02*Math.sin(Date.now()/100);
}
//update the UI every frame
window.requestAnimationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||(function(callback,element){setTimeout(callback,1000/60);});
function frame(){
requestAnimationFrame(frame);
updateUI();
}
frame(); //start frame loop
//function to (re)initialize UI
function initUI(){
drawMeter(I("dlMeter"),0,meterBk,dlColor,0);
drawMeter(I("ulMeter"),0,meterBk,ulColor,0);
I("dlText").textContent="";
I("ulText").textContent="";
I("pingText").textContent="";
I("jitText").textContent="";
I("ip").textContent="";
}
</script>
<style type="text/css">
html,body{
border:none; padding:0; margin:0;
background:#FFFFFF;
color:#202020;
}
body{
text-align:center;
font-family:"Roboto",sans-serif;
}
h1{
color:#404040;
}
#startStopBtn{
display:inline-block;
margin:0 auto;
color:#6060AA;
background-color:rgba(0,0,0,0);
border:0.15em solid #6060FF;
border-radius:0.3em;
transition:all 0.3s;
box-sizing:border-box;
width:8em; height:3em;
line-height:2.7em;
cursor:pointer;
box-shadow: 0 0 0 rgba(0,0,0,0.1), inset 0 0 0 rgba(0,0,0,0.1);
}
#startStopBtn:hover{
box-shadow: 0 0 2em rgba(0,0,0,0.1), inset 0 0 1em rgba(0,0,0,0.1);
}
#startStopBtn.running{
background-color:#FF3030;
border-color:#FF6060;
color:#FFFFFF;
}
#startStopBtn:before{
content:"Start";
}
#startStopBtn.running:before{
content:"Abort";
}
#test{
margin-top:2em;
margin-bottom:12em;
}
div.testArea{
display:inline-block;
width:16em;
height:12.5em;
position:relative;
box-sizing:border-box;
}
div.testArea2{
display:inline-block;
width:14em;
height:7em;
position:relative;
box-sizing:border-box;
text-align:center;
}
div.testArea div.testName{
position:absolute;
top:0.1em; left:0;
width:100%;
font-size:1.4em;
z-index:9;
}
div.testArea2 div.testName{
display:block;
text-align:center;
font-size:1.4em;
}
div.testArea div.meterText{
position:absolute;
bottom:1.55em; left:0;
width:100%;
font-size:2.5em;
z-index:9;
}
div.testArea2 div.meterText{
display:inline-block;
font-size:2.5em;
}
div.meterText:empty:before{
content:"0.00";
}
div.testArea div.unit{
position:absolute;
bottom:2em; left:0;
width:100%;
z-index:9;
}
div.testArea2 div.unit{
display:inline-block;
}
div.testArea canvas{
position:absolute;
top:0; left:0; width:100%; height:100%;
z-index:1;
}
div.testGroup{
display:block;
margin: 0 auto;
}
#shareArea{
width:95%;
max-width:40em;
margin:0 auto;
margin-top:2em;
}
#shareArea > *{
display:block;
width:100%;
height:auto;
margin: 0.25em 0;
}
#privacyPolicy{
position:fixed;
top:2em;
bottom:2em;
left:2em;
right:2em;
overflow-y:auto;
width:auto;
height:auto;
box-shadow:0 0 3em 1em #000000;
z-index:999999;
text-align:left;
background-color:#FFFFFF;
padding:1em;
}
a.privacy{
text-align:center;
font-size:0.8em;
color:#808080;
display:block;
}
@media all and (max-width:40em){
body{
font-size:0.8em;
}
}
</style>
<title><?= getenv('TITLE') ?: 'LibreSpeed Example' ?></title>
</head>
<body>
<h1><?= getenv('TITLE') ?: 'LibreSpeed Example' ?></h1>
<div id="testWrapper">
<div id="startStopBtn" onclick="startStop()"></div><br/>
<?php if(getenv("TELEMETRY")=="true"){ ?>
<a class="privacy" href="#" onclick="I('privacyPolicy').style.display=''">Privacy</a>
<?php } ?>
<div id="test">
<div class="testGroup">
<div class="testArea2">
<div class="testName">Ping</div>
<div id="pingText" class="meterText" style="color:#AA6060"></div>
<div class="unit">ms</div>
</div>
<div class="testArea2">
<div class="testName">Jitter</div>
<div id="jitText" class="meterText" style="color:#AA6060"></div>
<div class="unit">ms</div>
</div>
</div>
<div class="testGroup">
<div class="testArea">
<div class="testName">Download</div>
<canvas id="dlMeter" class="meter"></canvas>
<div id="dlText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
<div class="testArea">
<div class="testName">Upload</div>
<canvas id="ulMeter" class="meter"></canvas>
<div id="ulText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
</div>
<div id="ipArea">
<span id="ip"></span>
</div>
<div id="shareArea" style="display:none">
<h3>Share results</h3>
<p>Test ID: <span id="testId"></span></p>
<input type="text" value="" id="resultsURL" readonly="readonly" onclick="this.select();this.focus();this.select();document.execCommand('copy');alert('Link copied')"/>
<img src="" id="resultsImg" />
</div>
</div>
<a href="https://github.com/librespeed/speedtest">Source code</a>
</div>
<div id="privacyPolicy" style="display:none">
<h2>Privacy Policy</h2>
<p>This HTML5 Speedtest server is configured with telemetry enabled.</p>
<h4>What data we collect</h4>
<p>
At the end of the test, the following data is collected and stored:
<ul>
<li>Test ID</li>
<li>Time of testing</li>
<li>Test results (download and upload speed, ping and jitter)</li>
<li>IP address</li>
<li>ISP information</li>
<li>Approximate location (inferred from IP address, not GPS)</li>
<li>User agent and browser locale</li>
<li>Test log (contains no personal information)</li>
</ul>
</p>
<h4>How we use the data</h4>
<p>
Data collected through this service is used to:
<ul>
<li>Allow sharing of test results (sharable image for forums, etc.)</li>
<li>To improve the service offered to you (for instance, to detect problems on our side)</li>
</ul>
No personal information is disclosed to third parties.
</p>
<h4>Your consent</h4>
<p>
By starting the test, you consent to the terms of this privacy policy.
</p>
<h4>Data removal</h4>
<p>
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.<br/><br/>
Contact this email address for all deletion requests: <a href="mailto:<?=getenv("EMAIL") ?>"><?=getenv("EMAIL") ?></a>.
</p>
<br/><br/>
<a class="privacy" href="#" onclick="I('privacyPolicy').style.display='none'">Close</a><br/>
</div>
<script type="text/javascript">setTimeout(function(){initUI()},100);</script>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Binary file not shown.

View file

@ -1,72 +0,0 @@
<?php
define('ID_OBFUSCATION_SALT_FILE', __DIR__.'/idObfuscation_salt.php');
/**
* @return string|int
*/
function getObfuscationSalt()
{
if (!file_exists(ID_OBFUSCATION_SALT_FILE)) {
$bytes = openssl_random_pseudo_bytes(4);
$saltData = "<?php\n\n\$OBFUSCATION_SALT = 0x".bin2hex($bytes).";\n";
file_put_contents(ID_OBFUSCATION_SALT_FILE, $saltData);
}
if (
file_exists(ID_OBFUSCATION_SALT_FILE)
&& is_readable(ID_OBFUSCATION_SALT_FILE)
) {
require ID_OBFUSCATION_SALT_FILE;
}
return isset($OBFUSCATION_SALT) ? $OBFUSCATION_SALT : 0;
}
/**
* This is a simple reversible hash function I made for encoding and decoding test IDs.
* It is not cryptographically secure, don't use it to hash passwords or something!
*
* @param int|string $id
* @param bool $dec
*
* @return int|string
*/
function obfdeobf($id, $dec)
{
$salt = getObfuscationSalt() & 0xFFFFFFFF;
$id &= 0xFFFFFFFF;
if ($dec) {
$id ^= $salt;
$id = (($id & 0xAAAAAAAA) >> 1) | ($id & 0x55555555) << 1;
$id = (($id & 0x0000FFFF) << 16) | (($id & 0xFFFF0000) >> 16);
return $id;
}
$id = (($id & 0x0000FFFF) << 16) | (($id & 0xFFFF0000) >> 16);
$id = (($id & 0xAAAAAAAA) >> 1) | ($id & 0x55555555) << 1;
return $id ^ $salt;
}
/**
* @param int $id
*
* @return string
*/
function obfuscateId($id)
{
return str_pad(base_convert(obfdeobf($id + 1, false), 10, 36), 7, 0, STR_PAD_LEFT);
}
/**
* @param string $id
*
* @return int
*/
function deobfuscateId($id)
{
return obfdeobf(base_convert($id, 36, 10), true) - 1;
}

View file

@ -1,224 +0,0 @@
<?php
require_once 'telemetry_db.php';
error_reporting(0);
putenv('GDFONTPATH='.realpath('.'));
/**
* @param string $name
*
* @return string|null
*/
function tryFont($name)
{
if (is_array(imageftbbox(12, 0, $name, 'M'))) {
return $name;
}
$fullPathToFont = realpath('.').'/'.$name.'.ttf';
if (is_array(imageftbbox(12, 0, $fullPathToFont, 'M'))) {
return $fullPathToFont;
}
return null;
}
/**
* @param int|float $d
*
* @return string
*/
function format($d)
{
if ($d < 10) {
return number_format($d, 2, '.', '');
}
if ($d < 100) {
return number_format($d, 1, '.', '');
}
return number_format($d, 0, '.', '');
}
/**
* @param array $speedtest
*
* @return array
*/
function formatSpeedtestDataForImage($speedtest)
{
// format values for the image
$speedtest['dl'] = format($speedtest['dl']);
$speedtest['ul'] = format($speedtest['ul']);
$speedtest['ping'] = format($speedtest['ping']);
$speedtest['jit'] = format($speedtest['jitter']);
$speedtest['timestamp'] = $speedtest['timestamp'];
$ispinfo = json_decode($speedtest['ispinfo'], true)['processedString'];
$dash = strpos($ispinfo, '-');
if ($dash !== false) {
$ispinfo = substr($ispinfo, $dash + 2);
$par = strrpos($ispinfo, '(');
if ($par !== false) {
$ispinfo = substr($ispinfo, 0, $par);
}
} else {
$ispinfo = '';
}
$speedtest['ispinfo'] = $ispinfo;
return $speedtest;
}
/**
* @param array $speedtest
*
* @return void
*/
function drawImage($speedtest)
{
// format values for the image
$data = formatSpeedtestDataForImage($speedtest);
$dl = $data['dl'];
$ul = $data['ul'];
$ping = $data['ping'];
$jit = $data['jitter'];
$ispinfo = $data['ispinfo'];
$timestamp = $data['timestamp'];
// initialize the image
$SCALE = 1.25;
$SMALL_SEP = 8 * $SCALE;
$WIDTH = 400 * $SCALE;
$HEIGHT = 229 * $SCALE;
$im = imagecreatetruecolor($WIDTH, $HEIGHT);
$BACKGROUND_COLOR = imagecolorallocate($im, 255, 255, 255);
// configure fonts
$FONT_LABEL = tryFont('OpenSans-Semibold');
$FONT_LABEL_SIZE = 14 * $SCALE;
$FONT_LABEL_SIZE_BIG = 16 * $SCALE;
$FONT_METER = tryFont('OpenSans-Light');
$FONT_METER_SIZE = 20 * $SCALE;
$FONT_METER_SIZE_BIG = 22 * $SCALE;
$FONT_MEASURE = tryFont('OpenSans-Semibold');
$FONT_MEASURE_SIZE = 12 * $SCALE;
$FONT_MEASURE_SIZE_BIG = 12 * $SCALE;
$FONT_ISP = tryFont('OpenSans-Semibold');
$FONT_ISP_SIZE = 9 * $SCALE;
$FONT_TIMESTAMP = tryFont("OpenSans-Light");
$FONT_TIMESTAMP_SIZE = 8 * $SCALE;
$FONT_WATERMARK = tryFont('OpenSans-Light');
$FONT_WATERMARK_SIZE = 8 * $SCALE;
// configure text colors
$TEXT_COLOR_LABEL = imagecolorallocate($im, 40, 40, 40);
$TEXT_COLOR_PING_METER = imagecolorallocate($im, 170, 96, 96);
$TEXT_COLOR_JIT_METER = imagecolorallocate($im, 170, 96, 96);
$TEXT_COLOR_DL_METER = imagecolorallocate($im, 96, 96, 170);
$TEXT_COLOR_UL_METER = imagecolorallocate($im, 96, 96, 96);
$TEXT_COLOR_MEASURE = imagecolorallocate($im, 40, 40, 40);
$TEXT_COLOR_ISP = imagecolorallocate($im, 40, 40, 40);
$SEPARATOR_COLOR = imagecolorallocate($im, 192, 192, 192);
$TEXT_COLOR_TIMESTAMP = imagecolorallocate($im, 160, 160, 160);
$TEXT_COLOR_WATERMARK = imagecolorallocate($im, 160, 160, 160);
// configure positioning or the different parts on the image
$POSITION_X_PING = 125 * $SCALE;
$POSITION_Y_PING_LABEL = 24 * $SCALE;
$POSITION_Y_PING_METER = 60 * $SCALE;
$POSITION_Y_PING_MEASURE = 60 * $SCALE;
$POSITION_X_JIT = 275 * $SCALE;
$POSITION_Y_JIT_LABEL = 24 * $SCALE;
$POSITION_Y_JIT_METER = 60 * $SCALE;
$POSITION_Y_JIT_MEASURE = 60 * $SCALE;
$POSITION_X_DL = 120 * $SCALE;
$POSITION_Y_DL_LABEL = 105 * $SCALE;
$POSITION_Y_DL_METER = 143 * $SCALE;
$POSITION_Y_DL_MEASURE = 169 * $SCALE;
$POSITION_X_UL = 280 * $SCALE;
$POSITION_Y_UL_LABEL = 105 * $SCALE;
$POSITION_Y_UL_METER = 143 * $SCALE;
$POSITION_Y_UL_MEASURE = 169 * $SCALE;
$POSITION_X_ISP = 4 * $SCALE;
$POSITION_Y_ISP = 205 * $SCALE;
$SEPARATOR_Y = 211 * $SCALE;
$POSITION_X_TIMESTAMP= 4 * $SCALE;
$POSITION_Y_TIMESTAMP = 223 * $SCALE;
$POSITION_Y_WATERMARK = 223 * $SCALE;
// configure labels
$MBPS_TEXT = 'Mbps';
$MS_TEXT = 'ms';
$PING_TEXT = 'Ping';
$JIT_TEXT = 'Jitter';
$DL_TEXT = 'Download';
$UL_TEXT = 'Upload';
$WATERMARK_TEXT = 'LibreSpeed';
// create text boxes for each part of the image
$mbpsBbox = imageftbbox($FONT_MEASURE_SIZE_BIG, 0, $FONT_MEASURE, $MBPS_TEXT);
$msBbox = imageftbbox($FONT_MEASURE_SIZE, 0, $FONT_MEASURE, $MS_TEXT);
$pingBbox = imageftbbox($FONT_LABEL_SIZE, 0, $FONT_LABEL, $PING_TEXT);
$pingMeterBbox = imageftbbox($FONT_METER_SIZE, 0, $FONT_METER, $ping);
$jitBbox = imageftbbox($FONT_LABEL_SIZE, 0, $FONT_LABEL, $JIT_TEXT);
$jitMeterBbox = imageftbbox($FONT_METER_SIZE, 0, $FONT_METER, $jit);
$dlBbox = imageftbbox($FONT_LABEL_SIZE_BIG, 0, $FONT_LABEL, $DL_TEXT);
$dlMeterBbox = imageftbbox($FONT_METER_SIZE_BIG, 0, $FONT_METER, $dl);
$ulBbox = imageftbbox($FONT_LABEL_SIZE_BIG, 0, $FONT_LABEL, $UL_TEXT);
$ulMeterBbox = imageftbbox($FONT_METER_SIZE_BIG, 0, $FONT_METER, $ul);
$watermarkBbox = imageftbbox($FONT_WATERMARK_SIZE, 0, $FONT_WATERMARK, $WATERMARK_TEXT);
$POSITION_X_WATERMARK = $WIDTH - $watermarkBbox[4] - 4 * $SCALE;
// put the parts together to draw the image
imagefilledrectangle($im, 0, 0, $WIDTH, $HEIGHT, $BACKGROUND_COLOR);
// ping
imagefttext($im, $FONT_LABEL_SIZE, 0, $POSITION_X_PING - $pingBbox[4] / 2, $POSITION_Y_PING_LABEL, $TEXT_COLOR_LABEL, $FONT_LABEL, $PING_TEXT);
imagefttext($im, $FONT_METER_SIZE, 0, $POSITION_X_PING - $pingMeterBbox[4] / 2 - $msBbox[4] / 2 - $SMALL_SEP / 2, $POSITION_Y_PING_METER, $TEXT_COLOR_PING_METER, $FONT_METER, $ping);
imagefttext($im, $FONT_MEASURE_SIZE, 0, $POSITION_X_PING + $pingMeterBbox[4] / 2 + $SMALL_SEP / 2 - $msBbox[4] / 2, $POSITION_Y_PING_MEASURE, $TEXT_COLOR_MEASURE, $FONT_MEASURE, $MS_TEXT);
// jitter
imagefttext($im, $FONT_LABEL_SIZE, 0, $POSITION_X_JIT - $jitBbox[4] / 2, $POSITION_Y_JIT_LABEL, $TEXT_COLOR_LABEL, $FONT_LABEL, $JIT_TEXT);
imagefttext($im, $FONT_METER_SIZE, 0, $POSITION_X_JIT - $jitMeterBbox[4] / 2 - $msBbox[4] / 2 - $SMALL_SEP / 2, $POSITION_Y_JIT_METER, $TEXT_COLOR_JIT_METER, $FONT_METER, $jit);
imagefttext($im, $FONT_MEASURE_SIZE, 0, $POSITION_X_JIT + $jitMeterBbox[4] / 2 + $SMALL_SEP / 2 - $msBbox[4] / 2, $POSITION_Y_JIT_MEASURE, $TEXT_COLOR_MEASURE, $FONT_MEASURE, $MS_TEXT);
// dl
imagefttext($im, $FONT_LABEL_SIZE_BIG, 0, $POSITION_X_DL - $dlBbox[4] / 2, $POSITION_Y_DL_LABEL, $TEXT_COLOR_LABEL, $FONT_LABEL, $DL_TEXT);
imagefttext($im, $FONT_METER_SIZE_BIG, 0, $POSITION_X_DL - $dlMeterBbox[4] / 2, $POSITION_Y_DL_METER, $TEXT_COLOR_DL_METER, $FONT_METER, $dl);
imagefttext($im, $FONT_MEASURE_SIZE_BIG, 0, $POSITION_X_DL - $mbpsBbox[4] / 2, $POSITION_Y_DL_MEASURE, $TEXT_COLOR_MEASURE, $FONT_MEASURE, $MBPS_TEXT);
// ul
imagefttext($im, $FONT_LABEL_SIZE_BIG, 0, $POSITION_X_UL - $ulBbox[4] / 2, $POSITION_Y_UL_LABEL, $TEXT_COLOR_LABEL, $FONT_LABEL, $UL_TEXT);
imagefttext($im, $FONT_METER_SIZE_BIG, 0, $POSITION_X_UL - $ulMeterBbox[4] / 2, $POSITION_Y_UL_METER, $TEXT_COLOR_UL_METER, $FONT_METER, $ul);
imagefttext($im, $FONT_MEASURE_SIZE_BIG, 0, $POSITION_X_UL - $mbpsBbox[4] / 2, $POSITION_Y_UL_MEASURE, $TEXT_COLOR_MEASURE, $FONT_MEASURE, $MBPS_TEXT);
// isp
imagefttext($im, $FONT_ISP_SIZE, 0, $POSITION_X_ISP, $POSITION_Y_ISP, $TEXT_COLOR_ISP, $FONT_ISP, $ispinfo);
// separator
imagefilledrectangle($im, 0, $SEPARATOR_Y, $WIDTH, $SEPARATOR_Y, $SEPARATOR_COLOR);
// timestamp
imagefttext($im, $FONT_TIMESTAMP_SIZE, 0, $POSITION_X_TIMESTAMP, $POSITION_Y_TIMESTAMP, $TEXT_COLOR_TIMESTAMP, $FONT_TIMESTAMP, $timestamp);
// watermark
imagefttext($im, $FONT_WATERMARK_SIZE, 0, $POSITION_X_WATERMARK, $POSITION_Y_WATERMARK, $TEXT_COLOR_WATERMARK, $FONT_WATERMARK, $WATERMARK_TEXT);
// send the image to the browser
header('Content-Type: image/png');
imagepng($im);
}
$speedtest = getSpeedtestUserById($_GET['id']);
if (!is_array($speedtest)) {
exit(1);
}
drawImage($speedtest);

View file

@ -1,169 +0,0 @@
<?php
session_start();
error_reporting(0);
require 'telemetry_settings.php';
require_once 'telemetry_db.php';
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
?>
<!DOCTYPE html>
<html>
<head>
<title>LibreSpeed - Stats</title>
<style type="text/css">
html,body{
margin:0;
padding:0;
border:none;
width:100%; min-height:100%;
}
html{
background-color: hsl(198,72%,35%);
font-family: "Segoe UI","Roboto",sans-serif;
}
body{
background-color:#FFFFFF;
box-sizing:border-box;
width:100%;
max-width:70em;
margin:4em auto;
box-shadow:0 1em 6em #00000080;
padding:1em 1em 4em 1em;
border-radius:0.4em;
}
h1,h2,h3,h4,h5,h6{
font-weight:300;
margin-bottom: 0.1em;
}
h1{
text-align:center;
}
table{
margin:2em 0;
width:100%;
}
table, tr, th, td {
border: 1px solid #AAAAAA;
}
th {
width: 6em;
}
td {
word-break: break-all;
}
div {
margin: 1em 0;
}
</style>
</head>
<body>
<h1>LibreSpeed - Stats</h1>
<?php
if (!isset($stats_password) || $stats_password === 'PASSWORD') {
?>
Please set $stats_password in telemetry_settings.php to enable access.
<?php
} elseif ($_SESSION['logged'] === true) {
if ($_GET['op'] === 'logout') {
$_SESSION['logged'] = false;
?><script type="text/javascript">window.location=location.protocol+"//"+location.host+location.pathname;</script><?php
} else {
?>
<form action="stats.php" method="GET"><input type="hidden" name="op" value="logout" /><input type="submit" value="Logout" /></form>
<form action="stats.php" method="GET">
<h3>Search test results</h3>
<input type="hidden" name="op" value="id" />
<input type="text" name="id" id="id" placeholder="Test ID" value=""/>
<input type="submit" value="Find" />
<input type="submit" onclick="document.getElementById('id').value=''" value="Show last 100 tests" />
</form>
<?php
if ($_GET['op'] === 'id' && !empty($_GET['id'])) {
$speedtest = getSpeedtestUserById($_GET['id']);
$speedtests = [];
if (false === $speedtest) {
echo '<div>There was an error trying to fetch the speedtest result for ID "'.$_GET['id'].'".</div>';
} elseif (null === $speedtest) {
echo '<div>Could not find a speedtest result for ID "'.$_GET['id'].'".</div>';
} else {
$speedtests = [$speedtest];
}
} else {
$speedtests = getLatestSpeedtestUsers();
if (false === $speedtests) {
echo '<div>There was an error trying to fetch latest speedtest results.</div>';
} elseif (empty($speedtests)) {
echo '<div>Could not find any speedtest results in database.</div>';
}
}
foreach ($speedtests as $speedtest) {
?>
<table>
<tr>
<th>Test ID</th>
<td><?= htmlspecialchars($speedtest['id_formatted'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>Date and time</th>
<td><?= htmlspecialchars($speedtest['timestamp'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>IP and ISP Info</th>
<td>
<?= htmlspecialchars($speedtest['ip'], ENT_HTML5, 'UTF-8') ?><br/>
<?= htmlspecialchars($speedtest['ispinfo'], ENT_HTML5, 'UTF-8') ?>
</td>
</tr>
<tr>
<th>User agent and locale</th>
<td><?= htmlspecialchars($speedtest['ua'], ENT_HTML5, 'UTF-8') ?><br/>
<?= htmlspecialchars($speedtest['lang'], ENT_HTML5, 'UTF-8') ?>
</td>
</tr>
<tr>
<th>Download speed</th>
<td><?= htmlspecialchars($speedtest['dl'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>Upload speed</th>
<td><?= htmlspecialchars($speedtest['ul'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>Ping</th>
<td><?= htmlspecialchars($speedtest['ping'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>Jitter</th>
<td><?= htmlspecialchars($speedtest['jitter'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>Log</th>
<td><?= htmlspecialchars($speedtest['log'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
<tr>
<th>Extra info</th>
<td><?= htmlspecialchars($speedtest['extra'], ENT_HTML5, 'UTF-8') ?></td>
</tr>
</table>
<?php
}
}
} elseif ($_GET['op'] === 'login' && $_POST['password'] === $stats_password) {
$_SESSION['logged'] = true;
?><script type="text/javascript">window.location=location.protocol+"//"+location.host+location.pathname;</script><?php
} else {
?>
<form action="stats.php?op=login" method="POST">
<h3>Login</h3>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
<?php
}
?>
</body>
</html>

View file

@ -1,42 +0,0 @@
<?php
require 'telemetry_settings.php';
require_once 'telemetry_db.php';
$ip = $_SERVER['REMOTE_ADDR'];
$ispinfo = $_POST['ispinfo'];
$extra = $_POST['extra'];
$ua = $_SERVER['HTTP_USER_AGENT'];
$lang = '';
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
}
$dl = $_POST['dl'];
$ul = $_POST['ul'];
$ping = $_POST['ping'];
$jitter = $_POST['jitter'];
$log = $_POST['log'];
if (isset($redact_ip_addresses) && true === $redact_ip_addresses) {
$ip = '0.0.0.0';
$ipv4_regex = '/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/';
$ipv6_regex = '/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/';
$hostname_regex = '/"hostname":"([^\\\\"]|\\\\")*"/';
$ispinfo = preg_replace($ipv4_regex, '0.0.0.0', $ispinfo);
$ispinfo = preg_replace($ipv6_regex, '0.0.0.0', $ispinfo);
$ispinfo = preg_replace($hostname_regex, '"hostname":"REDACTED"', $ispinfo);
$log = preg_replace($ipv4_regex, '0.0.0.0', $log);
$log = preg_replace($ipv6_regex, '0.0.0.0', $log);
$log = preg_replace($hostname_regex, '"hostname":"REDACTED"', $log);
}
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
$id = insertSpeedtestUser($ip, $ispinfo, $extra, $ua, $lang, $dl, $ul, $ping, $jitter, $log);
if (false === $id) {
exit(1);
}
echo 'id '.$id;

View file

@ -1,220 +0,0 @@
<?php
require_once 'idObfuscation.php';
define('TELEMETRY_SETTINGS_FILE', 'telemetry_settings.php');
/**
* @return PDO|false
*/
function getPdo()
{
if (
!file_exists(TELEMETRY_SETTINGS_FILE)
|| !is_readable(TELEMETRY_SETTINGS_FILE)
) {
return false;
}
require TELEMETRY_SETTINGS_FILE;
if (!isset($db_type)) {
return false;
}
$pdoOptions = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try {
if ('mysql' === $db_type) {
if (!isset(
$MySql_hostname,
$MySql_port,
$MySql_databasename,
$MySql_username,
$MySql_password
)) {
return false;
}
$dsn = 'mysql:'
.'host='.$MySql_hostname
.';port='.$MySql_port
.';dbname='.$MySql_databasename;
return new PDO($dsn, $MySql_username, $MySql_password, $pdoOptions);
}
if ('sqlite' === $db_type) {
if (!isset($Sqlite_db_file)) {
return false;
}
$pdo = new PDO('sqlite:'.$Sqlite_db_file, null, null, $pdoOptions);
$pdo->exec('
CREATE TABLE IF NOT EXISTS `speedtest_users` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`ispinfo` text,
`extra` text,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ip` text NOT NULL,
`ua` text NOT NULL,
`lang` text NOT NULL,
`dl` text,
`ul` text,
`ping` text,
`jitter` text,
`log` longtext
);
');
return $pdo;
}
if ('postgresql' === $db_type) {
if (!isset(
$PostgreSql_hostname,
$PostgreSql_databasename,
$PostgreSql_username,
$PostgreSql_password
)) {
return false;
}
$dsn = 'pgsql:'
.'host='.$PostgreSql_hostname
.';dbname='.$PostgreSql_databasename;
return new PDO($dsn, $PostgreSql_username, $PostgreSql_password, $pdoOptions);
}
} catch (Exception $e) {
return false;
}
return false;
}
/**
* @return bool
*/
function isObfuscationEnabled()
{
require TELEMETRY_SETTINGS_FILE;
return
isset($enable_id_obfuscation)
&& true === $enable_id_obfuscation;
}
/**
* @return string|false returns the id of the inserted column or false on error
*/
function insertSpeedtestUser($ip, $ispinfo, $extra, $ua, $lang, $dl, $ul, $ping, $jitter, $log)
{
$pdo = getPdo();
if (!($pdo instanceof PDO)) {
return false;
}
try {
$stmt = $pdo->prepare(
'INSERT INTO speedtest_users
(ip,ispinfo,extra,ua,lang,dl,ul,ping,jitter,log)
VALUES (?,?,?,?,?,?,?,?,?,?)'
);
$stmt->execute([
$ip, $ispinfo, $extra, $ua, $lang, $dl, $ul, $ping, $jitter, $log
]);
$id = $pdo->lastInsertId();
} catch (Exception $e) {
return false;
}
if (isObfuscationEnabled()) {
return obfuscateId($id);
}
return $id;
}
/**
* @param int|string $id
*
* @return array|null|false returns the speedtest data as array, null
* if no data is found for the given id or
* false if there was an error
*
* @throws RuntimeException
*/
function getSpeedtestUserById($id)
{
$pdo = getPdo();
if (!($pdo instanceof PDO)) {
return false;
}
if (isObfuscationEnabled()) {
$id = deobfuscateId($id);
}
try {
$stmt = $pdo->prepare(
'SELECT
id, timestamp, ip, ispinfo, ua, lang, dl, ul, ping, jitter, log, extra
FROM speedtest_users
WHERE id = :id'
);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
return false;
}
if (!is_array($row)) {
return null;
}
$row['id_formatted'] = $row['id'];
if (isObfuscationEnabled()) {
$row['id_formatted'] = obfuscateId($row['id']).' (deobfuscated: '.$row['id'].')';
}
return $row;
}
/**
* @return array|false
*/
function getLatestSpeedtestUsers()
{
$pdo = getPdo();
if (!($pdo instanceof PDO)) {
return false;
}
try {
$stmt = $pdo->query(
'SELECT
id, timestamp, ip, ispinfo, ua, lang, dl, ul, ping, jitter, log, extra
FROM speedtest_users
ORDER BY timestamp DESC
LIMIT 100'
);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $i => $row) {
$rows[$i]['id_formatted'] = $row['id'];
if (isObfuscationEnabled()) {
$rows[$i]['id_formatted'] = obfuscateId($row['id']).' (deobfuscated: '.$row['id'].')';
}
}
} catch (Exception $e) {
return false;
}
return $rows;
}

View file

@ -1,59 +0,0 @@
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `speedtest_telemetry`
--
-- --------------------------------------------------------
--
-- Table structure for table `speedtest_users`
--
CREATE TABLE `speedtest_users` (
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ip` text NOT NULL,
`ispinfo` text,
`extra` text,
`ua` text NOT NULL,
`lang` text NOT NULL,
`dl` text,
`ul` text,
`ping` text,
`jitter` text,
`log` longtext
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `speedtest_users`
--
ALTER TABLE `speedtest_users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `speedtest_users`
--
ALTER TABLE `speedtest_users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View file

@ -1,113 +0,0 @@
--
-- PostgreSQL database dump
--
-- Dumped from database version 9.6.3
-- Dumped by pg_dump version 9.6.5
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: speedtest_users; Type: TABLE; Schema: public; Owner: speedtest
--
CREATE TABLE speedtest_users (
id integer NOT NULL,
"timestamp" timestamp without time zone DEFAULT now() NOT NULL,
ip text NOT NULL,
ispinfo text,
extra text,
ua text NOT NULL,
lang text NOT NULL,
dl text,
ul text,
ping text,
jitter text,
log text
);
-- Commented out the following line because it assumes the user of the speedtest server, @bplower
-- ALTER TABLE speedtest_users OWNER TO speedtest;
--
-- Name: speedtest_users_id_seq; Type: SEQUENCE; Schema: public; Owner: speedtest
--
CREATE SEQUENCE speedtest_users_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
-- Commented out the following line because it assumes the user of the speedtest server, @bplower
-- ALTER TABLE speedtest_users_id_seq OWNER TO speedtest;
--
-- Name: speedtest_users_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: speedtest
--
ALTER SEQUENCE speedtest_users_id_seq OWNED BY speedtest_users.id;
--
-- Name: speedtest_users id; Type: DEFAULT; Schema: public; Owner: speedtest
--
ALTER TABLE ONLY speedtest_users ALTER COLUMN id SET DEFAULT nextval('speedtest_users_id_seq'::regclass);
--
-- Data for Name: speedtest_users; Type: TABLE DATA; Schema: public; Owner: speedtest
--
COPY speedtest_users (id, "timestamp", ip, ua, lang, dl, ul, ping, jitter, log) FROM stdin;
\.
--
-- Name: speedtest_users_id_seq; Type: SEQUENCE SET; Schema: public; Owner: speedtest
--
SELECT pg_catalog.setval('speedtest_users_id_seq', 1, true);
--
-- Name: speedtest_users speedtest_users_pkey; Type: CONSTRAINT; Schema: public; Owner: speedtest
--
ALTER TABLE ONLY speedtest_users
ADD CONSTRAINT speedtest_users_pkey PRIMARY KEY (id);
--
-- PostgreSQL database dump complete
--

View file

@ -1,26 +0,0 @@
<?php
// Type of db: "mysql", "sqlite" or "postgresql"
$db_type = 'mysql';
// Password to login to stats.php. Change this!!!
$stats_password = 'PASSWORD';
// If set to true, test IDs will be obfuscated to prevent users from guessing URLs of other tests
$enable_id_obfuscation = false;
// If set to true, IP addresses will be redacted from IP and ISP info fields, as well as the log
$redact_ip_addresses = false;
// Sqlite3 settings
$Sqlite_db_file = '../../speedtest_telemetry.sql';
// Mysql settings
$MySql_username = 'USERNAME';
$MySql_password = 'PASSWORD';
$MySql_hostname = 'DB_HOSTNAME';
$MySql_databasename = 'DB_NAME';
$MySql_port = '3306';
// Postgresql settings
$PostgreSql_username = 'USERNAME';
$PostgreSql_password = 'PASSWORD';
$PostgreSql_hostname = 'DB_HOSTNAME';
$PostgreSql_databasename = 'DB_NAME';

View file

@ -1,379 +0,0 @@
/*
LibreSpeed - Main
by Federico Dossena
https://github.com/librespeed/speedtest/
GNU LGPLv3 License
*/
/*
This is the main interface between your webpage and the speedtest.
It hides the speedtest web worker to the page, and provides many convenient functions to control the test.
The best way to learn how to use this is to look at the basic example, but here's some documentation.
To initialize the test, create a new Speedtest object:
var s=new Speedtest();
Now you can think of this as a finite state machine. These are the states (use getState() to see them):
- 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.
- 1: here you can add test points. You only need to do this if you want to use multiple test points.
A server is defined as an object like this:
{
name: "User friendly name",
server:"http://yourBackend.com/", <---- URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
dlURL:"garbage.php" <----- path to garbage.php or its replacement on the server
ulURL:"empty.php" <----- path to empty.php or its replacement on the server
pingURL:"empty.php" <----- path to empty.php or its replacement on the server. This is used to ping the server by this selector
getIpURL:"getIP.php" <----- path to getIP.php or its replacement on the server
}
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.
- 2: test point selected, ready to start the test. Use start() to begin, this will move to state 3
- 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:
- dlStatus: download speed in mbps
- ulStatus: upload speed in mbps
- pingStatus: ping in ms
- jitterStatus: jitter in ms
- dlProgress: progress of the download test as a float 0-1
- ulProgress: progress of the upload test as a float 0-1
- pingProgress: progress of the ping/jitter test as a float 0-1
- testState: state of the test (-1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=aborted)
- clientIp: IP address of the client performing the test (and optionally ISP and distance)
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.
The test can be aborted at any time with abort().
At the end of the test, it will move to state 4
- 4: test finished. You can run it again by calling start() if you want.
*/
function Speedtest() {
this._serverList = []; //when using multiple points of test, this is a list of test points
this._selectedServer = null; //when using multiple points of test, this is the selected server
this._settings = {}; //settings for the speedtest worker
this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
console.log(
"LibreSpeed by Federico Dossena v5.2.3 - https://github.com/librespeed/speedtest"
);
}
Speedtest.prototype = {
constructor: Speedtest,
/**
* Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
*/
getState: function() {
return this._state;
},
/**
* Change one of the test settings from their defaults.
* - parameter: string with the name of the parameter that you want to set
* - value: new value for the parameter
*
* Invalid values or nonexistant parameters will be ignored by the speedtest worker.
*/
setParameter: function(parameter, value) {
if (this._state == 3)
throw "You cannot change the test settings while running the test";
this._settings[parameter] = value;
if(parameter === "telemetry_extra"){
this._originalExtra=this._settings.telemetry_extra;
}
},
/**
* Used internally to check if a server object contains all the required elements.
* Also fixes the server URL if needed.
*/
_checkServerDefinition: function(server) {
try {
if (typeof server.name !== "string")
throw "Name string missing from server definition (name)";
if (typeof server.server !== "string")
throw "Server address string missing from server definition (server)";
if (server.server.charAt(server.server.length - 1) != "/")
server.server += "/";
if (server.server.indexOf("//") == 0)
server.server = location.protocol + server.server;
if (typeof server.dlURL !== "string")
throw "Download URL string missing from server definition (dlURL)";
if (typeof server.ulURL !== "string")
throw "Upload URL string missing from server definition (ulURL)";
if (typeof server.pingURL !== "string")
throw "Ping URL string missing from server definition (pingURL)";
if (typeof server.getIpURL !== "string")
throw "GetIP URL string missing from server definition (getIpURL)";
} catch (e) {
throw "Invalid server definition";
}
},
/**
* Add a test point (multiple points of test)
* server: the server to be added as an object. Must contain the following elements:
* {
* name: "User friendly name",
* server:"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
* dlURL:"garbage.php" path to garbage.php or its replacement on the server
* ulURL:"empty.php" path to empty.php or its replacement on the server
* pingURL:"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
* getIpURL:"getIP.php" path to getIP.php or its replacement on the server
* }
*/
addTestPoint: function(server) {
this._checkServerDefinition(server);
if (this._state == 0) this._state = 1;
if (this._state != 1) throw "You can't add a server after server selection";
this._settings.mpot = true;
this._serverList.push(server);
},
/**
* Same as addTestPoint, but you can pass an array of servers
*/
addTestPoints: function(list) {
for (var i = 0; i < list.length; i++) this.addTestPoint(list[i]);
},
/**
* Load a JSON server list from URL (multiple points of test)
* url: the url where the server list can be fetched. Must be an array with objects containing the following elements:
* {
* "name": "User friendly name",
* "server":"http://yourBackend.com/", URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
* "dlURL":"garbage.php" path to garbage.php or its replacement on the server
* "ulURL":"empty.php" path to empty.php or its replacement on the server
* "pingURL":"empty.php" path to empty.php or its replacement on the server. This is used to ping the server by this selector
* "getIpURL":"getIP.php" path to getIP.php or its replacement on the server
* }
* 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
*/
loadServerList: function(url,result) {
if (this._state == 0) this._state = 1;
if (this._state != 1) throw "You can't add a server after server selection";
this._settings.mpot = true;
var xhr = new XMLHttpRequest();
xhr.onload = function(){
try{
var servers=JSON.parse(xhr.responseText);
for(var i=0;i<servers.length;i++){
this._checkServerDefinition(servers[i]);
}
this.addTestPoints(servers);
result(servers);
}catch(e){
result(null);
}
}.bind(this);
xhr.onerror = function(){result(null);}
xhr.open("GET",url);
xhr.send();
},
/**
* Returns the selected server (multiple points of test)
*/
getSelectedServer: function() {
if (this._state < 2 || this._selectedServer == null)
throw "No server is selected";
return this._selectedServer;
},
/**
* Manually selects one of the test points (multiple points of test)
*/
setSelectedServer: function(server) {
this._checkServerDefinition(server);
if (this._state == 3)
throw "You can't select a server while the test is running";
this._selectedServer = server;
this._state = 2;
},
/**
* Automatically selects a server from the list of added test points. The server with the lowest ping will be chosen. (multiple points of test)
* The process is asynchronous and the passed result callback function will be called when it's done, then the test can be started.
*/
selectServer: function(result) {
if (this._state != 1) {
if (this._state == 0) throw "No test points added";
if (this._state == 2) throw "Server already selected";
if (this._state >= 3)
throw "You can't select a server while the test is running";
}
if (this._selectServerCalled) throw "selectServer already called"; else this._selectServerCalled=true;
/*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.
*/
var select = function(serverList, selected) {
//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.
var PING_TIMEOUT = 2000;
var USE_PING_TIMEOUT = true; //will be disabled on unsupported browsers
if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) {
//IE11 doesn't support XHR timeout
USE_PING_TIMEOUT = false;
}
var ping = function(url, rtt) {
url += (url.match(/\?/) ? "&" : "?") + "cors=true";
var xhr = new XMLHttpRequest();
var t = new Date().getTime();
xhr.onload = function() {
if (xhr.responseText.length == 0) {
//we expect an empty response
var instspd = new Date().getTime() - t; //rough timing estimate
try {
//try to get more accurate timing using performance API
var p = performance.getEntriesByName(url);
p = p[p.length - 1];
var d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d;
} catch (e) {}
rtt(instspd);
} else rtt(-1);
}.bind(this);
xhr.onerror = function() {
rtt(-1);
}.bind(this);
xhr.open("GET", url);
if (USE_PING_TIMEOUT) {
try {
xhr.timeout = PING_TIMEOUT;
xhr.ontimeout = xhr.onerror;
} catch (e) {}
}
xhr.send();
}.bind(this);
//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.
var PINGS = 3, //up to 3 pings are performed, unless the server is down...
SLOW_THRESHOLD = 500; //...or one of the pings is above this threshold
var checkServer = function(server, done) {
var i = 0;
server.pingT = -1;
if (server.server.indexOf(location.protocol) == -1) done();
else {
var nextPing = function() {
if (i++ == PINGS) {
done();
return;
}
ping(
server.server + server.pingURL,
function(t) {
if (t >= 0) {
if (t < server.pingT || server.pingT == -1) server.pingT = t;
if (t < SLOW_THRESHOLD) nextPing();
else done();
} else done();
}.bind(this)
);
}.bind(this);
nextPing();
}
}.bind(this);
//check servers in list, one by one
var i = 0;
var done = function() {
var bestServer = null;
for (var i = 0; i < serverList.length; i++) {
if (
serverList[i].pingT != -1 &&
(bestServer == null || serverList[i].pingT < bestServer.pingT)
)
bestServer = serverList[i];
}
selected(bestServer);
}.bind(this);
var nextServer = function() {
if (i == serverList.length) {
done();
return;
}
checkServer(serverList[i++], nextServer);
}.bind(this);
nextServer();
}.bind(this);
//parallel server selection
var CONCURRENCY = 6;
var serverLists = [];
for (var i = 0; i < CONCURRENCY; i++) {
serverLists[i] = [];
}
for (var i = 0; i < this._serverList.length; i++) {
serverLists[i % CONCURRENCY].push(this._serverList[i]);
}
var completed = 0;
var bestServer = null;
for (var i = 0; i < CONCURRENCY; i++) {
select(
serverLists[i],
function(server) {
if (server != null) {
if (bestServer == null || server.pingT < bestServer.pingT)
bestServer = server;
}
completed++;
if (completed == CONCURRENCY) {
this._selectedServer = bestServer;
this._state = 2;
if (result) result(bestServer);
}
}.bind(this)
);
}
},
/**
* Starts the test.
* During the test, the onupdate(data) callback function will be called periodically with data from the worker.
* 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.
*/
start: function() {
if (this._state == 3) throw "Test already running";
this.worker = new Worker("speedtest_worker.js?r=" + Math.random());
this.worker.onmessage = function(e) {
if (e.data === this._prevData) return;
else this._prevData = e.data;
var data = JSON.parse(e.data);
try {
if (this.onupdate) this.onupdate(data);
} catch (e) {
console.error("Speedtest onupdate event threw exception: " + e);
}
if (data.testState >= 4) {
clearInterval(this.updater);
this._state = 4;
try {
if (this.onend) this.onend(data.testState == 5);
} catch (e) {
console.error("Speedtest onend event threw exception: " + e);
}
}
}.bind(this);
this.updater = setInterval(
function() {
this.worker.postMessage("status");
}.bind(this),
200
);
if (this._state == 1)
throw "When using multiple points of test, you must call selectServer before starting the test";
if (this._state == 2) {
this._settings.url_dl =
this._selectedServer.server + this._selectedServer.dlURL;
this._settings.url_ul =
this._selectedServer.server + this._selectedServer.ulURL;
this._settings.url_ping =
this._selectedServer.server + this._selectedServer.pingURL;
this._settings.url_getIp =
this._selectedServer.server + this._selectedServer.getIpURL;
if (typeof this._originalExtra !== "undefined") {
this._settings.telemetry_extra = JSON.stringify({
server: this._selectedServer.name,
extra: this._originalExtra
});
} else
this._settings.telemetry_extra = JSON.stringify({
server: this._selectedServer.name
});
}
this._state = 3;
this.worker.postMessage("start " + JSON.stringify(this._settings));
},
/**
* Aborts the test while it's running.
*/
abort: function() {
if (this._state < 3) throw "You cannot abort a test that's not started yet";
if (this._state < 4) this.worker.postMessage("abort");
}
};

View file

@ -1,724 +0,0 @@
/*
LibreSpeed - Worker
by Federico Dossena
https://github.com/librespeed/speedtest/
GNU LGPLv3 License
*/
// data reported to main thread
var testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
var dlStatus = ""; // download speed in megabit/s with 2 decimal digits
var ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
var pingStatus = ""; // ping in milliseconds with 2 decimal digits
var jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
var clientIp = ""; // client's IP address as reported by getIP.php
var dlProgress = 0; //progress of download test 0-1
var ulProgress = 0; //progress of upload test 0-1
var pingProgress = 0; //progress of ping+jitter test 0-1
var testId = null; //test ID (sent back by telemetry if used, null otherwise)
var log = ""; //telemetry log
function tlog(s) {
if (settings.telemetry_level >= 2) {
log += Date.now() + ": " + s + "\n";
}
}
function tverb(s) {
if (settings.telemetry_level >= 3) {
log += Date.now() + ": " + s + "\n";
}
}
function twarn(s) {
if (settings.telemetry_level >= 2) {
log += Date.now() + " WARN: " + s + "\n";
}
console.warn(s);
}
// test settings. can be overridden by sending specific values with the start command
var settings = {
mpot: false, //set to true when in MPOT mode
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
time_ul_max: 15, // max duration of upload test in seconds
time_dl_max: 15, // max duration of download test in seconds
time_auto: true, // if set to true, tests will take less time on faster connections
time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
count_ping: 10, // number of pings to perform in ping test
url_dl: "backend/garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
url_ul: "backend/empty.php", // path to an empty file, used for upload test. must be relative to this js file
url_ping: "backend/empty.php", // path to an empty file, used for ping test. must be relative to this js file
url_getIp: "backend/getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
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
xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
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)
xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
garbagePhp_chunkSize: 100, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
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
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.
overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
url_telemetry: "results/telemetry.php", // path to the script that adds telemetry data to the database
telemetry_extra: "", //extra data that can be passed to the telemetry through the settings
forceIE11Workaround: false //when set to true, it will foce the IE11 upload test on all browsers. Debug only
};
var xhr = null; // array of currently active xhr requests
var interval = null; // timer used in tests
var test_pointer = 0; //pointer to the next test to run inside settings.test_order
/*
this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
*/
function url_sep(url) {
return url.match(/\?/) ? "&" : "?";
}
/*
listener for commands from main thread to this worker.
commands:
-status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
-abort: aborts the current test
-start: starts the test. optionally, settings can be passed as JSON.
example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
*/
this.addEventListener("message", function(e) {
var params = e.data.split(" ");
if (params[0] === "status") {
// return status
postMessage(
JSON.stringify({
testState: testState,
dlStatus: dlStatus,
ulStatus: ulStatus,
pingStatus: pingStatus,
clientIp: clientIp,
jitterStatus: jitterStatus,
dlProgress: dlProgress,
ulProgress: ulProgress,
pingProgress: pingProgress,
testId: testId
})
);
}
if (params[0] === "start" && testState === -1) {
// start new test
testState = 0;
try {
// parse settings, if present
var s = {};
try {
var ss = e.data.substring(5);
if (ss) s = JSON.parse(ss);
} catch (e) {
twarn("Error parsing custom settings JSON. Please check your syntax");
}
//copy custom settings
for (var key in s) {
if (typeof settings[key] !== "undefined") settings[key] = s[key];
else twarn("Unknown setting ignored: " + key);
}
var ua = navigator.userAgent;
// quirks for specific browsers. apply only if not overridden. more may be added in future releases
if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
if (/Firefox.(\d+\.\d+)/i.test(ua)) {
if (typeof s.ping_allowPerformanceApi === "undefined") {
// ff performance API sucks
settings.ping_allowPerformanceApi = false;
}
}
if (/Edge.(\d+\.\d+)/i.test(ua)) {
if (typeof s.xhr_dlMultistream === "undefined") {
// edge more precise with 3 download streams
settings.xhr_dlMultistream = 3;
}
}
if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
if (typeof s.xhr_dlMultistream === "undefined") {
// chrome more precise with 5 streams
settings.xhr_dlMultistream = 5;
}
}
}
if (/Edge.(\d+\.\d+)/i.test(ua)) {
//Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
settings.forceIE11Workaround = true;
}
if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
//PS4 browser has the same bug as IE11/Edge
settings.forceIE11Workaround = true;
}
if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
//cheap af
//Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
settings.xhr_ul_blob_megabytes = 4;
}
if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
//Safari also needs the IE11 workaround but only for the MPOT version
settings.forceIE11Workaround = true;
}
//telemetry_level has to be parsed and not just copied
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
//transform test_order to uppercase, just in case
settings.test_order = settings.test_order.toUpperCase();
} catch (e) {
twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
}
// run the tests
tverb(JSON.stringify(settings));
test_pointer = 0;
var iRun = false,
dRun = false,
uRun = false,
pRun = false;
var runNextTest = function() {
if (testState == 5) return;
if (test_pointer >= settings.test_order.length) {
//test is finished
if (settings.telemetry_level > 0)
sendTelemetry(function(id) {
testState = 4;
if (id != null) testId = id;
});
else testState = 4;
return;
}
switch (settings.test_order.charAt(test_pointer)) {
case "I":
{
test_pointer++;
if (iRun) {
runNextTest();
return;
} else iRun = true;
getIp(runNextTest);
}
break;
case "D":
{
test_pointer++;
if (dRun) {
runNextTest();
return;
} else dRun = true;
testState = 1;
dlTest(runNextTest);
}
break;
case "U":
{
test_pointer++;
if (uRun) {
runNextTest();
return;
} else uRun = true;
testState = 3;
ulTest(runNextTest);
}
break;
case "P":
{
test_pointer++;
if (pRun) {
runNextTest();
return;
} else pRun = true;
testState = 2;
pingTest(runNextTest);
}
break;
case "_":
{
test_pointer++;
setTimeout(runNextTest, 1000);
}
break;
default:
test_pointer++;
}
};
runNextTest();
}
if (params[0] === "abort") {
// abort command
if (testState >= 4) return;
tlog("manually aborted");
clearRequests(); // stop all xhr activity
runNextTest = null;
if (interval) clearInterval(interval); // clear timer if present
if (settings.telemetry_level > 1) sendTelemetry(function() {});
testState = 5; //set test as aborted
dlStatus = "";
ulStatus = "";
pingStatus = "";
jitterStatus = "";
clientIp = "";
dlProgress = 0;
ulProgress = 0;
pingProgress = 0;
}
});
// stops all XHR activity, aggressively
function clearRequests() {
tverb("stopping pending XHRs");
if (xhr) {
for (var i = 0; i < xhr.length; i++) {
try {
xhr[i].onprogress = null;
xhr[i].onload = null;
xhr[i].onerror = null;
} catch (e) {}
try {
xhr[i].upload.onprogress = null;
xhr[i].upload.onload = null;
xhr[i].upload.onerror = null;
} catch (e) {}
try {
xhr[i].abort();
} catch (e) {}
try {
delete xhr[i];
} catch (e) {}
}
xhr = null;
}
}
// gets client's IP using url_getIp, then calls the done function
var ipCalled = false; // used to prevent multiple accidental calls to getIp
var ispInfo = ""; //used for telemetry
function getIp(done) {
tverb("getIp");
if (ipCalled) return;
else ipCalled = true; // getIp already called?
var startT = new Date().getTime();
xhr = new XMLHttpRequest();
xhr.onload = function() {
tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
try {
var data = JSON.parse(xhr.responseText);
clientIp = data.processedString;
ispInfo = data.rawIspInfo;
} catch (e) {
clientIp = xhr.responseText;
ispInfo = "";
}
done();
};
xhr.onerror = function() {
tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
done();
};
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);
xhr.send();
}
// download test, calls done function when it's over
var dlCalled = false; // used to prevent multiple accidental calls to dlTest
function dlTest(done) {
tverb("dlTest");
if (dlCalled) return;
else dlCalled = true; // dlTest already called?
var totLoaded = 0.0, // total number of loaded bytes
startT = new Date().getTime(), // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past
failed = false; // set to true if a stream fails
xhr = [];
// function to create a download stream. streams are slightly delayed so that they will not end at the same time
var testStream = function(i, delay) {
setTimeout(
function() {
if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
tverb("dl test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes loaded last time onprogress was called
var x = new XMLHttpRequest();
xhr[i] = x;
xhr[i].onprogress = function(event) {
tverb("dl stream progress event " + i + " " + event.loaded);
if (testState !== 1) {
try {
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the download test
// progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff;
prevLoaded = event.loaded;
}.bind(this);
xhr[i].onload = function() {
// the large file has been loaded entirely, start again
tverb("dl stream finished " + i);
try {
xhr[i].abort();
} catch (e) {} // reset the stream data to empty ram
testStream(i, 0);
}.bind(this);
xhr[i].onerror = function() {
// error
tverb("dl stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
try {
xhr[i].abort();
} catch (e) {}
delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
}.bind(this);
// send xhr
try {
if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
else xhr[i].responseType = "arraybuffer";
} catch (e) {}
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
xhr[i].send();
}.bind(this),
1 + delay
);
}.bind(this);
// open streams
for (var i = 0; i < settings.xhr_dlMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i);
}
// every 200ms, update dlStatus
interval = setInterval(
function() {
tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT;
if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
if (t < 200) return;
if (!graceTimeDone) {
if (t > 1000 * settings.time_dlGraceTime) {
if (totLoaded > 0) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date().getTime();
bonusT = 0;
totLoaded = 0.0;
}
graceTimeDone = true;
}
} else {
var speed = totLoaded / (t / 1000.0);
if (settings.time_auto) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (5.0 * speed) / 100000;
bonusT += bonus > 400 ? 400 : bonus;
}
//update status
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
if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
// test is over, stop streams and timer
if (failed || isNaN(dlStatus)) dlStatus = "Fail";
clearRequests();
clearInterval(interval);
dlProgress = 1;
tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this),
200
);
}
// upload test, calls done function whent it's over
var ulCalled = false; // used to prevent multiple accidental calls to ulTest
function ulTest(done) {
tverb("ulTest");
if (ulCalled) return;
else ulCalled = true; // ulTest already called?
// garbage data for upload test
var r = new ArrayBuffer(1048576);
var maxInt = Math.pow(2, 32) - 1;
try {
r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
} catch (e) {}
var req = [];
var reqsmall = [];
for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
req = new Blob(req);
r = new ArrayBuffer(262144);
try {
r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
} catch (e) {}
reqsmall.push(r);
reqsmall = new Blob(reqsmall);
var testFunction = function() {
var totLoaded = 0.0, // total number of transmitted bytes
startT = new Date().getTime(), // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past
failed = false; // set to true if a stream fails
xhr = [];
// function to create an upload stream. streams are slightly delayed so that they will not end at the same time
var testStream = function(i, delay) {
setTimeout(
function() {
if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
tverb("ul test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
var x = new XMLHttpRequest();
xhr[i] = x;
var ie11workaround;
if (settings.forceIE11Workaround) ie11workaround = true;
else {
try {
xhr[i].upload.onprogress;
ie11workaround = false;
} catch (e) {
ie11workaround = true;
}
}
if (ie11workaround) {
// 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
xhr[i].onload = xhr[i].onerror = function() {
tverb("ul stream progress event (ie11wa)");
totLoaded += reqsmall.size;
testStream(i, 0);
};
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
try {
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch (e) {}
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr[i].send(reqsmall);
} else {
// REGULAR version, no workaround
xhr[i].upload.onprogress = function(event) {
tverb("ul stream progress event " + i + " " + event.loaded);
if (testState !== 3) {
try {
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the upload test
// progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff;
prevLoaded = event.loaded;
}.bind(this);
xhr[i].upload.onload = function() {
// this stream sent all the garbage data, start again
tverb("ul stream finished " + i);
testStream(i, 0);
}.bind(this);
xhr[i].upload.onerror = function() {
tverb("ul stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
try {
xhr[i].abort();
} catch (e) {}
delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
}.bind(this);
// send xhr
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
try {
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
} catch (e) {}
//No Content-Type header in MPOT branch because it triggers bugs in some browsers
xhr[i].send(req);
}
}.bind(this),
delay
);
}.bind(this);
// open streams
for (var i = 0; i < settings.xhr_ulMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i);
}
// every 200ms, update ulStatus
interval = setInterval(
function() {
tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT;
if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
if (t < 200) return;
if (!graceTimeDone) {
if (t > 1000 * settings.time_ulGraceTime) {
if (totLoaded > 0) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date().getTime();
bonusT = 0;
totLoaded = 0.0;
}
graceTimeDone = true;
}
} else {
var speed = totLoaded / (t / 1000.0);
if (settings.time_auto) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (5.0 * speed) / 100000;
bonusT += bonus > 400 ? 400 : bonus;
}
//update status
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
if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
// test is over, stop streams and timer
if (failed || isNaN(ulStatus)) ulStatus = "Fail";
clearRequests();
clearInterval(interval);
ulProgress = 1;
tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this),
200
);
}.bind(this);
if (settings.mpot) {
tverb("Sending POST request before performing upload test");
xhr = [];
xhr[0] = new XMLHttpRequest();
xhr[0].onload = xhr[0].onerror = function() {
tverb("POST request sent, starting upload test");
testFunction();
}.bind(this);
xhr[0].open("POST", settings.url_ul);
xhr[0].send();
} else testFunction();
}
// ping+jitter test, function done is called when it's over
var ptCalled = false; // used to prevent multiple accidental calls to pingTest
function pingTest(done) {
tverb("pingTest");
if (ptCalled) return;
else ptCalled = true; // pingTest already called?
var startT = new Date().getTime(); //when the test was started
var prevT = null; // last time a pong was received
var ping = 0.0; // current ping value
var jitter = 0.0; // current jitter value
var i = 0; // counter of pongs received
var prevInstspd = 0; // last ping time, used for jitter calculation
xhr = [];
// ping function
var doPing = function() {
tverb("ping");
pingProgress = i / settings.count_ping;
prevT = new Date().getTime();
xhr[0] = new XMLHttpRequest();
xhr[0].onload = function() {
// pong
tverb("pong");
if (i === 0) {
prevT = new Date().getTime(); // first pong
} else {
var instspd = new Date().getTime() - prevT;
if (settings.ping_allowPerformanceApi) {
try {
//try to get accurate performance timing using performance api
var p = performance.getEntries();
p = p[p.length - 1];
var d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d;
} catch (e) {
//if not possible, keep the estimate
tverb("Performance API not supported, using estimate");
}
}
//noticed that some browsers randomly have 0ms ping
if (instspd < 1) instspd = prevInstspd;
if (instspd < 1) instspd = 1;
var instjitter = Math.abs(instspd - prevInstspd);
if (i === 1) ping = instspd;
/* first ping, can't tell jitter yet*/ else {
if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
if (i === 2) jitter = instjitter;
//discard the first jitter measurement because it might be much higher than it should be
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.
}
prevInstspd = instspd;
}
pingStatus = ping.toFixed(2);
jitterStatus = jitter.toFixed(2);
i++;
tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
if (i < settings.count_ping) doPing();
else {
// more pings to do?
pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}.bind(this);
xhr[0].onerror = function() {
// a ping failed, cancel test
tverb("ping failed");
if (settings.xhr_ignoreErrors === 0) {
//abort
pingStatus = "Fail";
jitterStatus = "Fail";
clearRequests();
tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
pingProgress = 1;
done();
}
if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
if (settings.xhr_ignoreErrors === 2) {
//ignore failed ping
i++;
if (i < settings.count_ping) doPing();
else {
// more pings to do?
pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this);
// send xhr
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
xhr[0].send();
}.bind(this);
doPing(); // start first ping
}
// telemetry
function sendTelemetry(done) {
if (settings.telemetry_level < 1) return;
xhr = new XMLHttpRequest();
xhr.onload = function() {
try {
var parts = xhr.responseText.split(" ");
if (parts[0] == "id") {
try {
var id = parts[1];
done(id);
} catch (e) {
done(null);
}
} else done(null);
} catch (e) {
done(null);
}
};
xhr.onerror = function() {
console.log("TELEMETRY ERROR " + xhr.status);
done(null);
};
xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
var telemetryIspInfo = {
processedString: clientIp,
rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
};
try {
var fd = new FormData();
fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
fd.append("dl", dlStatus);
fd.append("ul", ulStatus);
fd.append("ping", pingStatus);
fd.append("jitter", jitterStatus);
fd.append("log", settings.telemetry_level > 1 ? log : "");
fd.append("extra", settings.telemetry_extra);
xhr.send(fd);
} catch (ex) {
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 : "");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postData);
}
}