cidr-tools icon indicating copy to clipboard operation
cidr-tools copied to clipboard

Divide by zero error when merging unsorted IPv6 addresses

Open evelynhathaway opened this issue 2 years ago • 2 comments

I am using merge on an unsorted array of CIDR blocks and ran into this error for IPv6. I cannot reproduce the error in IPv4. I don't see a requirement in the documentation to sort the blocks before merging, so I believe it's a bug.

Minimal Reproduction

import {merge} from "cidr-tools";

// Works, returns an array of two CIDR blocks
merge([
	'1:1:1:1::/128',
	'1:1:1:2::/128',
]);

// Fails, throws a division by zero error
merge([
	'1:1:1:2::/128',
	'1:1:1:1::/128',
]);

Error

node_modules/cidr-tools/index.js:194
        start = ((part.end / biggest) - 1n) * biggest;
                           ^

RangeError: Division by zero
    at subparts (node_modules/cidr-tools/index.js:194:28)
    at merge (node_modules/cidr-tools/index.js:289:27)

Source Line of Code

https://github.com/silverwind/cidr-tools/blob/0ce9d7f537bc877bad59bf6e9b4c682d0d304f0a/index.js#L194

Versions

evelynhathaway avatar Oct 30 '23 18:10 evelynhathaway

Definitely a bug. The smallest numbers I could reproduce with is merge(["::2:0:0/128", "::1:0:0/128"]). At least safeguarding for division by zero does not fix it because the subparts function would recurse forever.

silverwind avatar Oct 30 '23 20:10 silverwind

I added a workaround that pre-sorts the networks in merge which does seem to resolve it. It's definitely not the right fix as merge should work with any sorting, but a real fix is likely not so trivial and that's why I'll keep this issue open.

silverwind avatar Oct 30 '23 21:10 silverwind