speedtest_worker.js 28 KB

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