Skip to content

Commit

Permalink
winget-source: Fix BIND_ADDRESS in Nodejs 18+
Browse files Browse the repository at this point in the history
When accessing a domain, nodejs would only use the first resolved IP (either v6 or v4) in onlookup(). When a IPv4 address is binded and the first DNS result is IPv6 address, internalConnect() would throw a bind error (as it calls libuv's IPv6-related function).

By giving family to globalAgent this bug is workarounded.
  • Loading branch information
taoky committed Jul 3, 2024
1 parent de6d301 commit 86cb634
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions winget-source/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,26 @@ const debugMode = process.env.DEBUG === 'true';
/** Local IP address to be bound to HTTPS requests. */
const localAddress = process.env.BIND_ADDRESS;

/**
* Get whether the given string is IPv4, v6 or neither, to workaround Node.js limitation
*
* @param {address} string The address
*
* @returns {int} 4 (IPv4), 6 (IPv6), or 0 (neither)
*/
function isIP(address) {
const ipv4Pattern = /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$/;
const ipv6Pattern = /^(([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)|(([0-9a-fA-F]{1,4}:){1,7}|:):(([0-9a-fA-F]{1,4}:){1,7}|:))$/;

if (ipv4Pattern.test(address)) {
return 4;
} else if (ipv6Pattern.test(address)) {
return 6;
} else {
return 0;
}
}

/**
* Get last modified date from HTTP response headers.
*
Expand Down Expand Up @@ -232,6 +252,7 @@ export function setupEnvironment() {
}
if (localAddress) {
https.globalAgent.options.localAddress = localAddress;
https.globalAgent.options.family = isIP(localAddress);
}
return {
debugMode,
Expand Down

0 comments on commit 86cb634

Please sign in to comment.