Skip to content

Commit

Permalink
Fix UV pool overflow and cancel outstanding HTTP requests on DNS succ…
Browse files Browse the repository at this point in the history
…ess (#69)

Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
Lucas Barrena and sindresorhus authored Apr 4, 2020
1 parent eb5f4b5 commit 0349077
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
47 changes: 40 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,31 @@ const publicIp = require('public-ip');
const pAny = require('p-any');
const pTimeout = require('p-timeout');

const appleCheck = async options => {
const {body} = await got('http://captive.apple.com/hotspot-detect.html', {
const appleCheck = options => {
const gotPromise = got('http://captive.apple.com/hotspot-detect.html', {
timeout: options.timeout,
family: options.version === 'v4' ? 4 : 6,
headers: {
'user-agent': 'CaptiveNetworkSupport/1.0 wispr'
}
});

return /Success/.test(body || '') || Promise.reject();
const promise = (async () => {
try {
const {body} = await gotPromise;
if (body && body.includes('Success')) {
throw new Error('Apple check failed');
}
} catch (error) {
if (!(error instanceof got.CancelError)) {
throw error;
}
}
})();

promise.cancel = gotPromise.cancel;

return promise;
};

const isOnline = options => {
Expand All @@ -22,19 +38,36 @@ const isOnline = options => {
...options
};

const queries = [];

const promise = pAny([
(async () => {
await publicIp[options.version]();
const query = publicIp[options.version](options);
queries.push(query);
await query;
return true;
})(),
(async () => {
await publicIp[options.version]({https: true});
const query = publicIp[options.version]({...options, onlyHttps: true});
queries.push(query);
await query;
return true;
})(),
appleCheck(options)
(async () => {
const query = appleCheck(options);
queries.push(query);
await query;
return true;
})()
]);

return pTimeout(promise, options.timeout).catch(() => false);
return pTimeout(promise, options.timeout).catch(() => {
for (const query of queries) {
query.cancel();
}

return false;
});
};

module.exports = isOnline;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"got": "^9.6.0",
"p-any": "^2.0.0",
"p-timeout": "^3.0.0",
"public-ip": "^3.0.0"
"public-ip": "^4.0.1"
},
"devDependencies": {
"ava": "^2.4.0",
Expand Down

0 comments on commit 0349077

Please sign in to comment.