speedtest_worker.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /*
  2. LibreSpeed - Worker
  3. by Federico Dossena
  4. https://github.com/librespeed/speedtest/
  5. GNU LGPLv3 License
  6. */
  7. // data reported to main thread
  8. let testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
  9. let dlStatus = ""; // download speed in megabit/s with 2 decimal digits
  10. let ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
  11. let pingStatus = ""; // ping in milliseconds with 2 decimal digits
  12. let jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
  13. let clientIp = ""; // client's IP address as reported by getIP.php
  14. let dlProgress = 0; //progress of download test 0-1
  15. let ulProgress = 0; //progress of upload test 0-1
  16. let pingProgress = 0; //progress of ping+jitter test 0-1
  17. let testId = null; //test ID (sent back by telemetry if used, null otherwise)
  18. let log = ""; //telemetry log
  19. function tlog(s) {
  20. if (settings.telemetry_level >= 2) {
  21. log += Date.now() + ": " + s + "\n";
  22. }
  23. }
  24. function tverb(s) {
  25. if (settings.telemetry_level >= 3) {
  26. log += Date.now() + ": " + s + "\n";
  27. }
  28. }
  29. function twarn(s) {
  30. if (settings.telemetry_level >= 2) {
  31. log += Date.now() + " WARN: " + s + "\n";
  32. }
  33. console.warn(s);
  34. }
  35. // test settings. can be overridden by sending specific values with the start command
  36. let settings = {
  37. mpot: false, //set to true when in MPOT mode
  38. 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
  39. time_ul_max: 15, // max duration of upload test in seconds
  40. time_dl_max: 15, // max duration of download test in seconds
  41. time_auto: true, // if set to true, tests will take less time on faster connections
  42. time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
  43. time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
  44. count_ping: 10, // number of pings to perform in ping test
  45. url_dl: "backend/garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
  46. url_ul: "backend/empty.php", // path to an empty file, used for upload test. must be relative to this js file
  47. url_ping: "backend/empty.php", // path to an empty file, used for ping test. must be relative to this js file
  48. url_getIp: "backend/getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
  49. getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
  50. 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
  51. xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
  52. xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
  53. xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
  54. xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
  55. 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)
  56. xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
  57. garbagePhp_chunkSize: 100, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
  58. 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
  59. 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.
  60. overheadCompensationFactor: 1.06, //can be changed to compensate for transport overhead. (see doc.md for some other values)
  61. useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
  62. telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
  63. url_telemetry: "results/telemetry.php", // path to the script that adds telemetry data to the database
  64. telemetry_extra: "", //extra data that can be passed to the telemetry through the settings
  65. forceIE11Workaround: false //when set to true, it will force the IE11 upload test on all browsers. Debug only
  66. };
  67. let xhr = null; // array of currently active xhr requests
  68. let interval = null; // timer used in tests
  69. let test_pointer = 0; //pointer to the next test to run inside settings.test_order
  70. /*
  71. this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
  72. */
  73. function url_sep(url) {
  74. return url.match(/\?/) ? "&" : "?";
  75. }
  76. /*
  77. listener for commands from main thread to this worker.
  78. commands:
  79. -status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
  80. -abort: aborts the current test
  81. -start: starts the test. optionally, settings can be passed as JSON.
  82. example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
  83. */
  84. this.addEventListener("message", function(e) {
  85. const params = e.data.split(" ");
  86. if (params[0] === "status") {
  87. // return status
  88. postMessage(
  89. JSON.stringify({
  90. testState: testState,
  91. dlStatus: dlStatus,
  92. ulStatus: ulStatus,
  93. pingStatus: pingStatus,
  94. clientIp: clientIp,
  95. jitterStatus: jitterStatus,
  96. dlProgress: dlProgress,
  97. ulProgress: ulProgress,
  98. pingProgress: pingProgress,
  99. testId: testId
  100. })
  101. );
  102. }
  103. if (params[0] === "start" && testState === -1) {
  104. // start new test
  105. testState = 0;
  106. try {
  107. // parse settings, if present
  108. let s = {};
  109. try {
  110. const ss = e.data.substring(5);
  111. if (ss) s = JSON.parse(ss);
  112. } catch (e) {
  113. twarn("Error parsing custom settings JSON. Please check your syntax");
  114. }
  115. //copy custom settings
  116. for (let key in s) {
  117. if (typeof settings[key] !== "undefined") settings[key] = s[key];
  118. else twarn("Unknown setting ignored: " + key);
  119. }
  120. const ua = navigator.userAgent;
  121. // quirks for specific browsers. apply only if not overridden. more may be added in future releases
  122. if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
  123. if (/Firefox.(\d+\.\d+)/i.test(ua)) {
  124. if (typeof s.ping_allowPerformanceApi === "undefined") {
  125. // ff performance API sucks
  126. settings.ping_allowPerformanceApi = false;
  127. }
  128. }
  129. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  130. if (typeof s.xhr_dlMultistream === "undefined") {
  131. // edge more precise with 3 download streams
  132. settings.xhr_dlMultistream = 3;
  133. }
  134. }
  135. if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
  136. if (typeof s.xhr_dlMultistream === "undefined") {
  137. // chrome more precise with 5 streams
  138. settings.xhr_dlMultistream = 5;
  139. }
  140. }
  141. }
  142. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  143. //Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
  144. settings.forceIE11Workaround = true;
  145. }
  146. if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
  147. //PS4 browser has the same bug as IE11/Edge
  148. settings.forceIE11Workaround = true;
  149. }
  150. if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
  151. //cheap af
  152. //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
  153. settings.xhr_ul_blob_megabytes = 4;
  154. }
  155. if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
  156. //Safari also needs the IE11 workaround but only for the MPOT version
  157. settings.forceIE11Workaround = true;
  158. }
  159. //telemetry_level has to be parsed and not just copied
  160. 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
  161. //transform test_order to uppercase, just in case
  162. settings.test_order = settings.test_order.toUpperCase();
  163. } catch (e) {
  164. twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
  165. }
  166. // run the tests
  167. tverb(JSON.stringify(settings));
  168. test_pointer = 0;
  169. let iRun = false,
  170. dRun = false,
  171. uRun = false,
  172. pRun = false;
  173. const runNextTest = function() {
  174. if (testState == 5) return;
  175. if (test_pointer >= settings.test_order.length) {
  176. //test is finished
  177. if (settings.telemetry_level > 0)
  178. sendTelemetry(function(id) {
  179. testState = 4;
  180. if (id != null) testId = id;
  181. });
  182. else testState = 4;
  183. return;
  184. }
  185. switch (settings.test_order.charAt(test_pointer)) {
  186. case "I":
  187. {
  188. test_pointer++;
  189. if (iRun) {
  190. runNextTest();
  191. return;
  192. } else iRun = true;
  193. getIp(runNextTest);
  194. }
  195. break;
  196. case "D":
  197. {
  198. test_pointer++;
  199. if (dRun) {
  200. runNextTest();
  201. return;
  202. } else dRun = true;
  203. testState = 1;
  204. dlTest(runNextTest);
  205. }
  206. break;
  207. case "U":
  208. {
  209. test_pointer++;
  210. if (uRun) {
  211. runNextTest();
  212. return;
  213. } else uRun = true;
  214. testState = 3;
  215. ulTest(runNextTest);
  216. }
  217. break;
  218. case "P":
  219. {
  220. test_pointer++;
  221. if (pRun) {
  222. runNextTest();
  223. return;
  224. } else pRun = true;
  225. testState = 2;
  226. pingTest(runNextTest);
  227. }
  228. break;
  229. case "_":
  230. {
  231. test_pointer++;
  232. setTimeout(runNextTest, 1000);
  233. }
  234. break;
  235. default:
  236. test_pointer++;
  237. }
  238. };
  239. runNextTest();
  240. }
  241. if (params[0] === "abort") {
  242. // abort command
  243. if (testState >= 4) return;
  244. tlog("manually aborted");
  245. clearRequests(); // stop all xhr activity
  246. runNextTest = null;
  247. if (interval) clearInterval(interval); // clear timer if present
  248. if (settings.telemetry_level > 1) sendTelemetry(function() {});
  249. testState = 5; //set test as aborted
  250. dlStatus = "";
  251. ulStatus = "";
  252. pingStatus = "";
  253. jitterStatus = "";
  254. clientIp = "";
  255. dlProgress = 0;
  256. ulProgress = 0;
  257. pingProgress = 0;
  258. }
  259. });
  260. // stops all XHR activity, aggressively
  261. function clearRequests() {
  262. tverb("stopping pending XHRs");
  263. if (xhr) {
  264. for (let i = 0; i < xhr.length; i++) {
  265. try {
  266. xhr[i].onprogress = null;
  267. xhr[i].onload = null;
  268. xhr[i].onerror = null;
  269. } catch (e) {}
  270. try {
  271. xhr[i].upload.onprogress = null;
  272. xhr[i].upload.onload = null;
  273. xhr[i].upload.onerror = null;
  274. } catch (e) {}
  275. try {
  276. xhr[i].abort();
  277. } catch (e) {}
  278. try {
  279. delete xhr[i];
  280. } catch (e) {}
  281. }
  282. xhr = null;
  283. }
  284. }
  285. // gets client's IP using url_getIp, then calls the done function
  286. let ipCalled = false; // used to prevent multiple accidental calls to getIp
  287. let ispInfo = ""; //used for telemetry
  288. function getIp(done) {
  289. tverb("getIp");
  290. if (ipCalled) return;
  291. else ipCalled = true; // getIp already called?
  292. let startT = new Date().getTime();
  293. xhr = new XMLHttpRequest();
  294. xhr.onload = function() {
  295. tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
  296. try {
  297. const data = JSON.parse(xhr.responseText);
  298. clientIp = data.processedString;
  299. ispInfo = data.rawIspInfo;
  300. } catch (e) {
  301. clientIp = xhr.responseText;
  302. ispInfo = "";
  303. }
  304. done();
  305. };
  306. xhr.onerror = function() {
  307. tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
  308. done();
  309. };
  310. 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);
  311. xhr.send();
  312. }
  313. // download test, calls done function when it's over
  314. let dlCalled = false; // used to prevent multiple accidental calls to dlTest
  315. function dlTest(done) {
  316. tverb("dlTest");
  317. if (dlCalled) return;
  318. else dlCalled = true; // dlTest already called?
  319. let totLoaded = 0.0, // total number of loaded bytes
  320. startT = new Date().getTime(), // timestamp when test was started
  321. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  322. graceTimeDone = false, //set to true after the grace time is past
  323. failed = false; // set to true if a stream fails
  324. xhr = [];
  325. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  326. const testStream = function(i, delay) {
  327. setTimeout(
  328. function() {
  329. if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
  330. tverb("dl test stream started " + i + " " + delay);
  331. let prevLoaded = 0; // number of bytes loaded last time onprogress was called
  332. let x = new XMLHttpRequest();
  333. xhr[i] = x;
  334. xhr[i].onprogress = function(event) {
  335. tverb("dl stream progress event " + i + " " + event.loaded);
  336. if (testState !== 1) {
  337. try {
  338. x.abort();
  339. } catch (e) {}
  340. } // just in case this XHR is still running after the download test
  341. // progress event, add number of new loaded bytes to totLoaded
  342. const loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  343. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  344. totLoaded += loadDiff;
  345. prevLoaded = event.loaded;
  346. }.bind(this);
  347. xhr[i].onload = function() {
  348. // the large file has been loaded entirely, start again
  349. tverb("dl stream finished " + i);
  350. try {
  351. xhr[i].abort();
  352. } catch (e) {} // reset the stream data to empty ram
  353. testStream(i, 0);
  354. }.bind(this);
  355. xhr[i].onerror = function() {
  356. // error
  357. tverb("dl stream failed " + i);
  358. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  359. try {
  360. xhr[i].abort();
  361. } catch (e) {}
  362. delete xhr[i];
  363. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  364. }.bind(this);
  365. // send xhr
  366. try {
  367. if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
  368. else xhr[i].responseType = "arraybuffer";
  369. } catch (e) {}
  370. 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
  371. xhr[i].send();
  372. }.bind(this),
  373. 1 + delay
  374. );
  375. }.bind(this);
  376. // open streams
  377. for (let i = 0; i < settings.xhr_dlMultistream; i++) {
  378. testStream(i, settings.xhr_multistreamDelay * i);
  379. }
  380. // every 200ms, update dlStatus
  381. interval = setInterval(
  382. function() {
  383. tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
  384. const t = new Date().getTime() - startT;
  385. if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
  386. if (t < 200) return;
  387. if (!graceTimeDone) {
  388. if (t > 1000 * settings.time_dlGraceTime) {
  389. if (totLoaded > 0) {
  390. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  391. startT = new Date().getTime();
  392. bonusT = 0;
  393. totLoaded = 0.0;
  394. }
  395. graceTimeDone = true;
  396. }
  397. } else {
  398. const speed = totLoaded / (t / 1000.0);
  399. if (settings.time_auto) {
  400. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  401. const bonus = (5.0 * speed) / 100000;
  402. bonusT += bonus > 400 ? 400 : bonus;
  403. }
  404. //update status
  405. 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
  406. if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
  407. // test is over, stop streams and timer
  408. if (failed || isNaN(dlStatus)) dlStatus = "Fail";
  409. clearRequests();
  410. clearInterval(interval);
  411. dlProgress = 1;
  412. tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
  413. done();
  414. }
  415. }
  416. }.bind(this),
  417. 200
  418. );
  419. }
  420. // upload test, calls done function when it's over
  421. let ulCalled = false; // used to prevent multiple accidental calls to ulTest
  422. function ulTest(done) {
  423. tverb("ulTest");
  424. if (ulCalled) return;
  425. else ulCalled = true; // ulTest already called?
  426. // garbage data for upload test
  427. let r = new ArrayBuffer(1048576);
  428. const maxInt = Math.pow(2, 32) - 1;
  429. try {
  430. r = new Uint32Array(r);
  431. for (let i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  432. } catch (e) {}
  433. let req = [];
  434. let reqsmall = [];
  435. for (let i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
  436. req = new Blob(req);
  437. r = new ArrayBuffer(262144);
  438. try {
  439. r = new Uint32Array(r);
  440. for (let i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
  441. } catch (e) {}
  442. reqsmall.push(r);
  443. reqsmall = new Blob(reqsmall);
  444. const testFunction = function() {
  445. let totLoaded = 0.0, // total number of transmitted bytes
  446. startT = new Date().getTime(), // timestamp when test was started
  447. bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
  448. graceTimeDone = false, //set to true after the grace time is past
  449. failed = false; // set to true if a stream fails
  450. xhr = [];
  451. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  452. const testStream = function(i, delay) {
  453. setTimeout(
  454. function() {
  455. if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
  456. tverb("ul test stream started " + i + " " + delay);
  457. let prevLoaded = 0; // number of bytes transmitted last time onprogress was called
  458. let x = new XMLHttpRequest();
  459. xhr[i] = x;
  460. let ie11workaround;
  461. if (settings.forceIE11Workaround) ie11workaround = true;
  462. else {
  463. try {
  464. xhr[i].upload.onprogress;
  465. ie11workaround = false;
  466. } catch (e) {
  467. ie11workaround = true;
  468. }
  469. }
  470. if (ie11workaround) {
  471. // IE11 workaround: 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
  472. xhr[i].onload = xhr[i].onerror = function() {
  473. tverb("ul stream progress event (ie11wa)");
  474. totLoaded += reqsmall.size;
  475. testStream(i, 0);
  476. };
  477. 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
  478. try {
  479. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  480. } catch (e) {}
  481. //No Content-Type header in MPOT branch because it triggers bugs in some browsers
  482. xhr[i].send(reqsmall);
  483. } else {
  484. // REGULAR version, no workaround
  485. xhr[i].upload.onprogress = function(event) {
  486. tverb("ul stream progress event " + i + " " + event.loaded);
  487. if (testState !== 3) {
  488. try {
  489. x.abort();
  490. } catch (e) {}
  491. } // just in case this XHR is still running after the upload test
  492. // progress event, add number of new loaded bytes to totLoaded
  493. const loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
  494. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
  495. totLoaded += loadDiff;
  496. prevLoaded = event.loaded;
  497. }.bind(this);
  498. xhr[i].upload.onload = function() {
  499. // this stream sent all the garbage data, start again
  500. tverb("ul stream finished " + i);
  501. testStream(i, 0);
  502. }.bind(this);
  503. xhr[i].upload.onerror = function() {
  504. tverb("ul stream failed " + i);
  505. if (settings.xhr_ignoreErrors === 0) failed = true; //abort
  506. try {
  507. xhr[i].abort();
  508. } catch (e) {}
  509. delete xhr[i];
  510. if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
  511. }.bind(this);
  512. // send xhr
  513. 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
  514. try {
  515. xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
  516. } catch (e) {}
  517. //No Content-Type header in MPOT branch because it triggers bugs in some browsers
  518. xhr[i].send(req);
  519. }
  520. }.bind(this),
  521. delay
  522. );
  523. }.bind(this);
  524. // open streams
  525. for (let i = 0; i < settings.xhr_ulMultistream; i++) {
  526. testStream(i, settings.xhr_multistreamDelay * i);
  527. }
  528. // every 200ms, update ulStatus
  529. interval = setInterval(
  530. function() {
  531. tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
  532. const t = new Date().getTime() - startT;
  533. if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
  534. if (t < 200) return;
  535. if (!graceTimeDone) {
  536. if (t > 1000 * settings.time_ulGraceTime) {
  537. if (totLoaded > 0) {
  538. // if the connection is so slow that we didn't get a single chunk yet, do not reset
  539. startT = new Date().getTime();
  540. bonusT = 0;
  541. totLoaded = 0.0;
  542. }
  543. graceTimeDone = true;
  544. }
  545. } else {
  546. const speed = totLoaded / (t / 1000.0);
  547. if (settings.time_auto) {
  548. //decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
  549. const bonus = (5.0 * speed) / 100000;
  550. bonusT += bonus > 400 ? 400 : bonus;
  551. }
  552. //update status
  553. 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
  554. if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
  555. // test is over, stop streams and timer
  556. if (failed || isNaN(ulStatus)) ulStatus = "Fail";
  557. clearRequests();
  558. clearInterval(interval);
  559. ulProgress = 1;
  560. tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
  561. done();
  562. }
  563. }
  564. }.bind(this),
  565. 200
  566. );
  567. }.bind(this);
  568. if (settings.mpot) {
  569. tverb("Sending POST request before performing upload test");
  570. xhr = [];
  571. xhr[0] = new XMLHttpRequest();
  572. xhr[0].onload = xhr[0].onerror = function() {
  573. tverb("POST request sent, starting upload test");
  574. testFunction();
  575. }.bind(this);
  576. xhr[0].open("POST", settings.url_ul);
  577. xhr[0].send();
  578. } else testFunction();
  579. }
  580. // ping+jitter test, function done is called when it's over
  581. let ptCalled = false; // used to prevent multiple accidental calls to pingTest
  582. function pingTest(done) {
  583. tverb("pingTest");
  584. if (ptCalled) return;
  585. else ptCalled = true; // pingTest already called?
  586. const startT = new Date().getTime(); //when the test was started
  587. let prevT = null; // last time a pong was received
  588. let ping = 0.0; // current ping value
  589. let jitter = 0.0; // current jitter value
  590. let i = 0; // counter of pongs received
  591. let prevInstspd = 0; // last ping time, used for jitter calculation
  592. xhr = [];
  593. // ping function
  594. const doPing = function() {
  595. tverb("ping");
  596. pingProgress = i / settings.count_ping;
  597. prevT = new Date().getTime();
  598. xhr[0] = new XMLHttpRequest();
  599. xhr[0].onload = function() {
  600. // pong
  601. tverb("pong");
  602. if (i === 0) {
  603. prevT = new Date().getTime(); // first pong
  604. } else {
  605. let instspd = new Date().getTime() - prevT;
  606. if (settings.ping_allowPerformanceApi) {
  607. try {
  608. //try to get accurate performance timing using performance api
  609. let p = performance.getEntries();
  610. p = p[p.length - 1];
  611. let d = p.responseStart - p.requestStart;
  612. if (d <= 0) d = p.duration;
  613. if (d > 0 && d < instspd) instspd = d;
  614. } catch (e) {
  615. //if not possible, keep the estimate
  616. tverb("Performance API not supported, using estimate");
  617. }
  618. }
  619. //noticed that some browsers randomly have 0ms ping
  620. if (instspd < 1) instspd = prevInstspd;
  621. if (instspd < 1) instspd = 1;
  622. const instjitter = Math.abs(instspd - prevInstspd);
  623. if (i === 1) ping = instspd;
  624. /* first ping, can't tell jitter yet*/ else {
  625. if (instspd < ping) ping = instspd; // update ping, if the instant ping is lower
  626. if (i === 2) jitter = instjitter;
  627. //discard the first jitter measurement because it might be much higher than it should be
  628. 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.
  629. }
  630. prevInstspd = instspd;
  631. }
  632. pingStatus = ping.toFixed(2);
  633. jitterStatus = jitter.toFixed(2);
  634. i++;
  635. tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
  636. if (i < settings.count_ping) doPing();
  637. else {
  638. // more pings to do?
  639. pingProgress = 1;
  640. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  641. done();
  642. }
  643. }.bind(this);
  644. xhr[0].onerror = function() {
  645. // a ping failed, cancel test
  646. tverb("ping failed");
  647. if (settings.xhr_ignoreErrors === 0) {
  648. //abort
  649. pingStatus = "Fail";
  650. jitterStatus = "Fail";
  651. clearRequests();
  652. tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
  653. pingProgress = 1;
  654. done();
  655. }
  656. if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
  657. if (settings.xhr_ignoreErrors === 2) {
  658. //ignore failed ping
  659. i++;
  660. if (i < settings.count_ping) doPing();
  661. else {
  662. // more pings to do?
  663. pingProgress = 1;
  664. tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
  665. done();
  666. }
  667. }
  668. }.bind(this);
  669. // send xhr
  670. 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
  671. xhr[0].send();
  672. }.bind(this);
  673. doPing(); // start first ping
  674. }
  675. // telemetry
  676. function sendTelemetry(done) {
  677. if (settings.telemetry_level < 1) return;
  678. xhr = new XMLHttpRequest();
  679. xhr.onload = function() {
  680. try {
  681. const parts = xhr.responseText.split(" ");
  682. if (parts[0] == "id") {
  683. try {
  684. let id = parts[1];
  685. done(id);
  686. } catch (e) {
  687. done(null);
  688. }
  689. } else done(null);
  690. } catch (e) {
  691. done(null);
  692. }
  693. };
  694. xhr.onerror = function() {
  695. console.log("TELEMETRY ERROR " + xhr.status);
  696. done(null);
  697. };
  698. xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
  699. const telemetryIspInfo = {
  700. processedString: clientIp,
  701. rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
  702. };
  703. try {
  704. const fd = new FormData();
  705. fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
  706. fd.append("dl", dlStatus);
  707. fd.append("ul", ulStatus);
  708. fd.append("ping", pingStatus);
  709. fd.append("jitter", jitterStatus);
  710. fd.append("log", settings.telemetry_level > 1 ? log : "");
  711. fd.append("extra", settings.telemetry_extra);
  712. xhr.send(fd);
  713. } catch (ex) {
  714. const 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 : "");
  715. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  716. xhr.send(postData);
  717. }
  718. }