fix(function): handle mask 0 and panic in ipv4_to_cidr/ipv6_to_cidr (#10733)

* fix(function): handle mask 0 and panic in ipv4_to_cidr/ipv6_to_cidr

Fixes #10732

Signed-off-by: Boaz Shuster <boaz.shuster.github@gmail.com>

* fix(function): invalid IPs return NULL in ipv4_to_cidr/ipv6_to_cidr

Fixes #10732

Signed-off-by: Boaz Shuster <boaz.shuster.github@gmail.com>

---------

Signed-off-by: Boaz Shuster <boaz.shuster.github@gmail.com>
Co-authored-by: Boaz Shuster <boaz.shuster.github@gmail.com>
This commit is contained in:
boaz2026
2026-11-30 23:45:57 +00:00
committed by GitHub
co-authored by Boaz Shuster
parent 36b079dabf
commit 710c81ef2b
3 changed files with 229 additions and 99 deletions
+163 -99
View File
@@ -12,11 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::net::{Ipv4Addr, Ipv6Addr};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use std::sync::Arc;
use common_query::error::{InvalidFuncArgsSnafu, Result};
use common_query::error::InvalidFuncArgsSnafu;
use datafusion_common::arrow::array::{Array, AsArray, StringViewBuilder};
use datafusion_common::arrow::compute;
use datafusion_common::arrow::datatypes::{DataType, UInt8Type};
@@ -113,56 +113,42 @@ impl Function for Ipv4ToCidr {
for i in 0..ip_vec.len() {
let ip_str = ip_vec.is_valid(i).then(|| ip_vec.value(i));
let subnet = subnets.and_then(|v| v.is_valid(i).then(|| v.value(i)));
let cidr = match (ip_str, subnet) {
(Some(ip_str), Some(mask)) => {
if ip_str.is_empty() {
return Err(DataFusionError::Execution("empty IPv4 address".to_string()));
let cidr = (|| {
let ip_str = ip_str?;
let ip_addr = complete_and_parse_ipv4(ip_str)?;
let subnet_mask = match subnets {
Some(subnets) => {
if subnets.is_null(i) {
return None;
}
subnets.value(i)
}
None => {
let ip_bits = u32::from(ip_addr);
let dots = ip_str.chars().filter(|&c| c == '.').count();
let ip_addr = complete_and_parse_ipv4(ip_str)?;
// Apply the subnet mask to the IP by zeroing out the host bits
let mask_bits = u32::MAX.wrapping_shl(32 - mask as u32);
let masked_ip = Ipv4Addr::from(u32::from(ip_addr) & mask_bits);
Some(format!("{}/{}", masked_ip, mask))
}
(Some(ip_str), None) => {
if ip_str.is_empty() {
return Err(DataFusionError::Execution("empty IPv4 address".to_string()));
}
let ip_addr = complete_and_parse_ipv4(ip_str)?;
// Determine the subnet mask based on trailing zeros or dots
let ip_bits = u32::from(ip_addr);
let dots = ip_str.chars().filter(|&c| c == '.').count();
let subnet_mask = match dots {
0 => 8, // If just one number like "192", use /8
1 => 16, // If two numbers like "192.168", use /16
2 => 24, // If three numbers like "192.168.1", use /24
_ => {
// For complete addresses, use trailing zeros
let trailing_zeros = ip_bits.trailing_zeros();
// Round to 8-bit boundaries if it's not a complete mask
if trailing_zeros % 8 == 0 {
32 - trailing_zeros.min(32) as u8
} else {
32 - (trailing_zeros as u8 / 8) * 8
match dots {
0 => 8, // If just one number like "192", use /8
1 => 16, // If two numbers like "192.168", use /16
2 => 24, // If three numbers like "192.168.1", use /24
_ => {
// For complete addresses, use trailing zeros
let trailing_zeros = ip_bits.trailing_zeros();
// Round to 8-bit boundaries if it's not a complete mask
if trailing_zeros % 8 == 0 {
32 - trailing_zeros.min(32) as u8
} else {
32 - (trailing_zeros as u8 / 8) * 8
}
}
}
};
}
};
// Apply the subnet mask to zero out host bits
let mask_bits = u32::MAX.wrapping_shl(32 - subnet_mask as u32);
let masked_ip = Ipv4Addr::from(ip_bits & mask_bits);
Some(format!("{}/{}", masked_ip, subnet_mask))
}
_ => None,
};
to_cidr(ip_addr.into(), subnet_mask)
})();
builder.append_option(cidr.as_deref());
}
@@ -242,38 +228,23 @@ impl Function for Ipv6ToCidr {
for i in 0..size {
let ip_str = ip_vec.is_valid(i).then(|| ip_vec.value(i));
let subnet = subnets.and_then(|v| v.is_valid(i).then(|| v.value(i)));
let cidr = match (ip_str, subnet) {
(Some(ip_str), Some(mask)) => {
if ip_str.is_empty() {
return Err(DataFusionError::Execution("empty IPv6 address".to_string()));
let cidr = (|| {
let ip_str = ip_str?;
let ip_addr = complete_and_parse_ipv6(ip_str)?;
let subnet_mask = match subnets {
Some(subnets) => {
if subnets.is_null(i) {
return None;
}
subnets.value(i)
}
None => auto_detect_ipv6_subnet(&ip_addr),
};
let ip_addr = complete_and_parse_ipv6(ip_str)?;
// Apply the subnet mask to the IP
let masked_ip = mask_ipv6(&ip_addr, mask);
Some(format!("{}/{}", masked_ip, mask))
}
(Some(ip_str), None) => {
if ip_str.is_empty() {
return Err(DataFusionError::Execution("empty IPv6 address".to_string()));
}
let ip_addr = complete_and_parse_ipv6(ip_str)?;
// Determine subnet based on address parts
let subnet_mask = auto_detect_ipv6_subnet(&ip_addr);
// Apply the subnet mask
let masked_ip = mask_ipv6(&ip_addr, subnet_mask);
Some(format!("{}/{}", masked_ip, subnet_mask))
}
_ => None,
};
to_cidr(ip_addr.into(), subnet_mask)
})();
builder.append_option(cidr.as_deref());
}
@@ -284,10 +255,16 @@ impl Function for Ipv6ToCidr {
// Helper functions
fn complete_and_parse_ipv4(ip_str: &str) -> Result<Ipv4Addr> {
/// Parses an IPv4 address, completing missing octets with zeros ("192.168" -> 192.168.0.0).
/// Returns `None` for an empty or invalid address.
fn complete_and_parse_ipv4(ip_str: &str) -> Option<Ipv4Addr> {
if ip_str.is_empty() {
return None;
}
// Try to parse as is
if let Ok(addr) = Ipv4Addr::from_str(ip_str) {
return Ok(addr);
return Some(addr);
}
// Count the dots to see how many octets we have
@@ -301,18 +278,20 @@ fn complete_and_parse_ipv4(ip_str: &str) -> Result<Ipv4Addr> {
_ => ip_str.to_string(),
};
Ipv4Addr::from_str(&completed).map_err(|_| {
InvalidFuncArgsSnafu {
err_msg: format!("Invalid IPv4 address: {}", ip_str),
}
.build()
})
Ipv4Addr::from_str(&completed).ok()
}
fn complete_and_parse_ipv6(ip_str: &str) -> Result<Ipv6Addr> {
/// Parses an IPv6 address, completing a partial one with "::" ("2001:db8" -> 2001:db8::).
/// Returns `None` for an empty or invalid address.
fn complete_and_parse_ipv6(ip_str: &str) -> Option<Ipv6Addr> {
// An empty string would otherwise be completed to "::"
if ip_str.is_empty() {
return None;
}
// If it's already a valid IPv6 address, just parse it
if let Ok(addr) = Ipv6Addr::from_str(ip_str) {
return Ok(addr);
return Some(addr);
}
// For partial addresses, try to complete them
@@ -325,12 +304,29 @@ fn complete_and_parse_ipv6(ip_str: &str) -> Result<Ipv6Addr> {
ip_str.to_string()
};
Ipv6Addr::from_str(&completed).map_err(|_| {
InvalidFuncArgsSnafu {
err_msg: format!("Invalid IPv6 address: {}", ip_str),
Ipv6Addr::from_str(&completed).ok()
}
/// Formats `ip` in CIDR notation with the host bits cleared,
/// or returns `None` if `prefix_len` is longer than the address.
fn to_cidr(ip: IpAddr, prefix_len: u8) -> Option<String> {
let masked: IpAddr = match ip {
IpAddr::V4(v4) if u32::from(prefix_len) <= Ipv4Addr::BITS => {
Ipv4Addr::from(u32::from(v4) & ipv4_mask_bits(prefix_len)).into()
}
.build()
})
IpAddr::V6(v6) if u32::from(prefix_len) <= Ipv6Addr::BITS => {
mask_ipv6(&v6, prefix_len).into()
}
_ => return None,
};
Some(format!("{masked}/{prefix_len}"))
}
/// Returns the IPv4 network mask for a prefix length in `0..=32`.
fn ipv4_mask_bits(prefix_len: u8) -> u32 {
u32::MAX
.checked_shl(32 - u32::from(prefix_len))
.unwrap_or(0)
}
fn mask_ipv6(addr: &Ipv6Addr, subnet: u8) -> Ipv6Addr {
@@ -401,7 +397,7 @@ fn auto_detect_ipv6_subnet(addr: &Ipv6Addr) -> u8 {
#[cfg(test)]
mod tests {
use arrow_schema::Field;
use datafusion_common::arrow::array::{StringViewArray, UInt8Array};
use datafusion_common::arrow::array::{ArrayRef, Int64Array, StringViewArray, UInt8Array};
use super::*;
@@ -512,7 +508,7 @@ mod tests {
let ipv4_func = Ipv4ToCidr::default();
let ipv6_func = Ipv6ToCidr::default();
// Empty string should fail
// Empty string yields NULL
let empty_values = vec![""];
let arg0 = ColumnarValue::Array(Arc::new(StringViewArray::from_iter_values(&empty_values)));
@@ -523,13 +519,13 @@ mod tests {
return_field: Arc::new(Field::new("x", DataType::Utf8View, false)),
config_options: Arc::new(Default::default()),
};
let ipv4_result = ipv4_func.invoke_with_args(args.clone());
let ipv6_result = ipv6_func.invoke_with_args(args);
let ipv4_result = ipv4_func.invoke_with_args(args.clone()).unwrap();
let ipv6_result = ipv6_func.invoke_with_args(args).unwrap();
assert!(ipv4_result.is_err());
assert!(ipv6_result.is_err());
assert!(ipv4_result.to_array(1).unwrap().is_null(0));
assert!(ipv6_result.to_array(1).unwrap().is_null(0));
// Invalid IP formats should fail
// Invalid IP formats yield NULL
let invalid_values = vec!["not an ip", "192.168.1.256", "zzzz::ffff"];
let arg0 =
ColumnarValue::Array(Arc::new(StringViewArray::from_iter_values(&invalid_values)));
@@ -541,8 +537,76 @@ mod tests {
return_field: Arc::new(Field::new("x", DataType::Utf8View, false)),
config_options: Arc::new(Default::default()),
};
let ipv4_result = ipv4_func.invoke_with_args(args);
let ipv4_result = ipv4_func.invoke_with_args(args.clone()).unwrap();
let ipv6_result = ipv6_func.invoke_with_args(args).unwrap();
assert!(ipv4_result.is_err());
let ipv4_result = ipv4_result.to_array(3).unwrap();
let ipv6_result = ipv6_result.to_array(3).unwrap();
assert!((0..3).all(|i| ipv4_result.is_null(i) && ipv6_result.is_null(i)));
// Empty and invalid IPs yield NULL with an explicit subnet mask too
let ip_values = ["", "not an ip"];
let subnets: ArrayRef = Arc::new(UInt8Array::from(vec![24, 24]));
let ipv4_result = ipv4_func
.invoke_with_args(make_subnet_args(&ip_values, subnets.clone()))
.unwrap();
let ipv6_result = ipv6_func
.invoke_with_args(make_subnet_args(&ip_values, subnets))
.unwrap();
let ipv4_result = ipv4_result.to_array(2).unwrap();
let ipv6_result = ipv6_result.to_array(2).unwrap();
assert!((0..2).all(|i| ipv4_result.is_null(i) && ipv6_result.is_null(i)));
}
fn make_subnet_args(ip_values: &[&str], subnet_values: ArrayRef) -> ScalarFunctionArgs {
let arg0 = ColumnarValue::Array(Arc::new(StringViewArray::from_iter_values(ip_values)));
let arg1 = ColumnarValue::Array(subnet_values);
ScalarFunctionArgs {
args: vec![arg0, arg1],
arg_fields: vec![],
number_rows: ip_values.len(),
return_field: Arc::new(Field::new("x", DataType::Utf8View, true)),
config_options: Arc::new(Default::default()),
}
}
#[test]
fn test_to_cidr_with_subnet_edge_cases() {
// Prefix 0 clears every bit, the maximum prefix keeps the full address.
// Out-of-range, NULL, and non-UInt8 subnet masks yield NULL instead of auto-detecting.
let ips = ["192.168.1.1"; 7];
let subnets = Arc::new(Int64Array::from(vec![
Some(0),
Some(32),
Some(33),
Some(255),
Some(256),
Some(-1),
None,
]));
let args = make_subnet_args(&ips, subnets);
let result = Ipv4ToCidr::default().invoke_with_args(args).unwrap();
let result = result.to_array(ips.len()).unwrap();
let result = result.as_string_view();
assert_eq!(result.value(0), "0.0.0.0/0");
assert_eq!(result.value(1), "192.168.1.1/32");
assert!((2..ips.len()).all(|i| result.is_null(i)));
let ips = ["2001:db8::1"; 5];
let subnets = Arc::new(UInt8Array::from(vec![
Some(0),
Some(128),
Some(129),
Some(255),
None,
]));
let args = make_subnet_args(&ips, subnets);
let result = Ipv6ToCidr::default().invoke_with_args(args).unwrap();
let result = result.to_array(ips.len()).unwrap();
let result = result.as_string_view();
assert_eq!(result.value(0), "::/0");
assert_eq!(result.value(1), "2001:db8::1/128");
assert!((2..ips.len()).all(|i| result.is_null(i)));
}
}
@@ -330,6 +330,48 @@ ORDER BY total_bytes DESC;
| fe80::/48 | 1 | 65536 |
+-----------------+--------------+-------------+
-- Subnet mask edge cases: 0 clears every bit, out-of-range and NULL masks yield NULL
SELECT
ipv4_to_cidr('192.168.1.1', 0) AS v4_mask_0,
ipv4_to_cidr('192.168.1.1', 32) AS v4_mask_32,
ipv4_to_cidr('192.168.1.1', 33) AS v4_mask_33,
ipv4_to_cidr('192.168.1.1', 256) AS v4_mask_256,
ipv4_to_cidr('192.168.1.1', -1) AS v4_mask_neg,
ipv4_to_cidr('192.168.1.1', arrow_cast(NULL, 'UInt8')) AS v4_mask_null;
+-----------+----------------+------------+-------------+-------------+--------------+
| v4_mask_0 | v4_mask_32 | v4_mask_33 | v4_mask_256 | v4_mask_neg | v4_mask_null |
+-----------+----------------+------------+-------------+-------------+--------------+
| 0.0.0.0/0 | 192.168.1.1/32 | | | | |
+-----------+----------------+------------+-------------+-------------+--------------+
SELECT
ipv6_to_cidr('2001:db8::1', arrow_cast(0, 'UInt8')) AS v6_mask_0,
ipv6_to_cidr('2001:db8::1', arrow_cast(128, 'UInt8')) AS v6_mask_128,
ipv6_to_cidr('2001:db8::1', arrow_cast(129, 'UInt8')) AS v6_mask_129,
ipv6_to_cidr('2001:db8::1', arrow_cast(NULL, 'UInt8')) AS v6_mask_null;
+-----------+-----------------+-------------+--------------+
| v6_mask_0 | v6_mask_128 | v6_mask_129 | v6_mask_null |
+-----------+-----------------+-------------+--------------+
| ::/0 | 2001:db8::1/128 | | |
+-----------+-----------------+-------------+--------------+
-- Empty and invalid IP addresses yield NULL
SELECT
ipv4_to_cidr('abc', 24) AS v4_invalid,
ipv4_to_cidr('', 24) AS v4_empty,
ipv4_to_cidr('abc') AS v4_invalid_auto,
ipv6_to_cidr('zzzz::ffff', arrow_cast(64, 'UInt8')) AS v6_invalid,
ipv6_to_cidr('', arrow_cast(64, 'UInt8')) AS v6_empty,
ipv6_to_cidr('') AS v6_empty_auto;
+------------+----------+-----------------+------------+----------+---------------+
| v4_invalid | v4_empty | v4_invalid_auto | v6_invalid | v6_empty | v6_empty_auto |
+------------+----------+-----------------+------------+----------+---------------+
| | | | | | |
+------------+----------+-----------------+------------+----------+---------------+
drop table ip_v4_data;
Affected Rows: 0
@@ -192,6 +192,30 @@ WHERE source_ip LIKE '%:%'
GROUP BY ipv6_to_cidr(source_ip, arrow_cast(48,'UInt8'))
ORDER BY total_bytes DESC;
-- Subnet mask edge cases: 0 clears every bit, out-of-range and NULL masks yield NULL
SELECT
ipv4_to_cidr('192.168.1.1', 0) AS v4_mask_0,
ipv4_to_cidr('192.168.1.1', 32) AS v4_mask_32,
ipv4_to_cidr('192.168.1.1', 33) AS v4_mask_33,
ipv4_to_cidr('192.168.1.1', 256) AS v4_mask_256,
ipv4_to_cidr('192.168.1.1', -1) AS v4_mask_neg,
ipv4_to_cidr('192.168.1.1', arrow_cast(NULL, 'UInt8')) AS v4_mask_null;
SELECT
ipv6_to_cidr('2001:db8::1', arrow_cast(0, 'UInt8')) AS v6_mask_0,
ipv6_to_cidr('2001:db8::1', arrow_cast(128, 'UInt8')) AS v6_mask_128,
ipv6_to_cidr('2001:db8::1', arrow_cast(129, 'UInt8')) AS v6_mask_129,
ipv6_to_cidr('2001:db8::1', arrow_cast(NULL, 'UInt8')) AS v6_mask_null;
-- Empty and invalid IP addresses yield NULL
SELECT
ipv4_to_cidr('abc', 24) AS v4_invalid,
ipv4_to_cidr('', 24) AS v4_empty,
ipv4_to_cidr('abc') AS v4_invalid_auto,
ipv6_to_cidr('zzzz::ffff', arrow_cast(64, 'UInt8')) AS v6_invalid,
ipv6_to_cidr('', arrow_cast(64, 'UInt8')) AS v6_empty,
ipv6_to_cidr('') AS v6_empty_auto;
drop table ip_v4_data;
drop table ip_v6_data;