Skip to content

Commit

Permalink
Make IPv6 parsing code compatible with Node 10
Browse files Browse the repository at this point in the history
  • Loading branch information
murgatroid99 committed Nov 5, 2021
1 parent 1a60c4f commit b1be84a
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions packages/grpc-js/src/channelz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ export function unregisterChannelzRef(ref: ChannelRef | SubchannelRef | ServerRe
}

/**
* Parses a single section of an IPv6 address as two bytes
* Parse a single section of an IPv6 address as two bytes
* @param addressSection A hexadecimal string of length up to 4
* @returns The pair of bytes representing this address section
*/
Expand All @@ -402,6 +402,21 @@ function parseIPv6Section(addressSection: string): [number, number] {
return [numberValue / 256 | 0, numberValue % 256];
}

/**
* Parse a chunk of an IPv6 address string to some number of bytes
* @param addressChunk Some number of segments of up to 4 hexadecimal
* characters each, joined by colons.
* @returns The list of bytes representing this address chunk
*/
function parseIPv6Chunk(addressChunk: string): number[] {
if (addressChunk === '') {
return [];
}
const bytePairs = addressChunk.split(':').map(section => parseIPv6Section(section));
const result: number[] = [];
return result.concat(...bytePairs);
}

/**
* Converts an IPv4 or IPv6 address from string representation to binary
* representation
Expand All @@ -413,17 +428,17 @@ function ipAddressStringToBuffer(ipAddress: string): Buffer | null {
return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment))));
} else if (isIPv6(ipAddress)) {
let leftSection: string;
let rightSection: string | null;
let rightSection: string;
const doubleColonIndex = ipAddress.indexOf('::');
if (doubleColonIndex === -1) {
leftSection = ipAddress;
rightSection = null;
rightSection = '';
} else {
leftSection = ipAddress.substring(0, doubleColonIndex);
rightSection = ipAddress.substring(doubleColonIndex + 2);
}
const leftBuffer = Buffer.from(leftSection.split(':').map(segment => parseIPv6Section(segment)).flat());
const rightBuffer = rightSection ? Buffer.from(rightSection.split(':').map(segment => parseIPv6Section(segment)).flat()) : Buffer.alloc(0);
const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection));
const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection));
const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0);
return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]);
} else {
Expand Down

0 comments on commit b1be84a

Please sign in to comment.