1use crate::compiler::prelude::*;
2use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3
4fn ip_subnet(value: &Value, mask: &Value) -> Resolved {
5 let value: IpAddr = value
6 .try_bytes_utf8_lossy()?
7 .parse()
8 .map_err(|err| format!("unable to parse IP address: {err}"))?;
9 let mask = mask.try_bytes_utf8_lossy()?;
10 let mask = if mask.starts_with('/') {
11 let subnet = parse_subnet(&mask)?;
13 match value {
14 IpAddr::V4(_) => {
15 if subnet > 32 {
16 return Err("subnet cannot be greater than 32 for ipv4 addresses".into());
17 }
18
19 ipv4_mask(subnet)
20 }
21 IpAddr::V6(_) => {
22 if subnet > 128 {
23 return Err("subnet cannot be greater than 128 for ipv6 addresses".into());
24 }
25
26 ipv6_mask(subnet)
27 }
28 }
29 } else {
30 mask.parse()
32 .map_err(|err| format!("unable to parse mask: {err}"))?
33 };
34 Ok(mask_ips(value, mask)?.to_string().into())
35}
36
37#[derive(Clone, Copy, Debug)]
38pub struct IpSubnet;
39
40impl Function for IpSubnet {
41 fn identifier(&self) -> &'static str {
42 "ip_subnet"
43 }
44
45 fn usage(&self) -> &'static str {
46 indoc! {"
47 Extracts the subnet address from the `ip` using the supplied `subnet`.
48 "}
49 }
50
51 fn category(&self) -> &'static str {
52 Category::Ip.as_ref()
53 }
54
55 fn internal_failure_reasons(&self) -> &'static [&'static str] {
56 &[
57 "`ip` is not a valid IP address.",
58 "`subnet` is not a valid subnet.",
59 ]
60 }
61
62 fn return_kind(&self) -> u16 {
63 kind::BYTES
64 }
65
66 fn notices(&self) -> &'static [&'static str] {
67 &[indoc! {"
68 Works with both IPv4 and IPv6 addresses. The IP version for the mask must be the same as
69 the supplied address.
70 "}]
71 }
72
73 fn parameters(&self) -> &'static [Parameter] {
74 const PARAMETERS: &[Parameter] = &[
75 Parameter::required("value", kind::BYTES, "The IP address (v4 or v6)."),
76 Parameter::required("subnet", kind::BYTES, "The subnet to extract from the IP address. This can be either a prefix length like `/8` or a net mask
77like `255.255.0.0`. The net mask can be either an IPv4 or IPv6 address."),
78 ];
79 PARAMETERS
80 }
81
82 fn examples(&self) -> &'static [Example] {
83 &[
84 example! {
85 title: "IPv4 subnet",
86 source: r#"ip_subnet!("192.168.10.32", "255.255.255.0")"#,
87 result: Ok("192.168.10.0"),
88 },
89 example! {
90 title: "IPv6 subnet",
91 source: r#"ip_subnet!("2404:6800:4003:c02::64", "/32")"#,
92 result: Ok("2404:6800::"),
93 },
94 example! {
95 title: "Subnet /1",
96 source: r#"ip_subnet!("192.168.0.1", "/1")"#,
97 result: Ok("128.0.0.0"),
98 },
99 ]
100 }
101
102 fn compile(
103 &self,
104 _state: &state::TypeState,
105 _ctx: &mut FunctionCompileContext,
106 arguments: ArgumentList,
107 ) -> Compiled {
108 let value = arguments.required("value");
109 let subnet = arguments.required("subnet");
110
111 Ok(IpSubnetFn { value, subnet }.as_expr())
112 }
113}
114
115#[derive(Debug, Clone)]
116struct IpSubnetFn {
117 value: Box<dyn Expression>,
118 subnet: Box<dyn Expression>,
119}
120
121impl FunctionExpression for IpSubnetFn {
122 fn resolve(&self, ctx: &mut Context) -> Resolved {
123 let value = self.value.resolve(ctx)?;
124 let mask = self.subnet.resolve(ctx)?;
125
126 ip_subnet(&value, &mask)
127 }
128
129 fn type_def(&self, _: &state::TypeState) -> TypeDef {
130 TypeDef::bytes().fallible()
131 }
132}
133
134fn parse_subnet(subnet: &str) -> ExpressionResult<u32> {
136 let subnet = subnet[1..]
137 .parse()
138 .map_err(|_| format!("{subnet} is not a valid subnet"))?;
139 Ok(subnet)
140}
141
142fn mask_ips(ip: IpAddr, mask: IpAddr) -> ExpressionResult<IpAddr> {
144 match (ip, mask) {
145 (IpAddr::V4(addr), IpAddr::V4(mask)) => {
146 let addr: u32 = addr.into();
147 let mask: u32 = mask.into();
148 Ok(Ipv4Addr::from(addr & mask).into())
149 }
150 (IpAddr::V6(addr), IpAddr::V6(mask)) => {
151 let mut masked = [0; 8];
152 for ((masked, addr), mask) in masked
153 .iter_mut()
154 .zip(addr.segments().iter())
155 .zip(mask.segments().iter())
156 {
157 *masked = addr & mask;
158 }
159
160 Ok(IpAddr::from(masked))
161 }
162 (IpAddr::V6(_), IpAddr::V4(_)) => {
163 Err("attempting to mask an ipv6 address with an ipv4 mask".into())
164 }
165 (IpAddr::V4(_), IpAddr::V6(_)) => {
166 Err("attempting to mask an ipv4 address with an ipv6 mask".into())
167 }
168 }
169}
170
171fn ipv4_mask(subnet_bits: u32) -> IpAddr {
173 let bits = !0u32 << (32 - subnet_bits);
174 Ipv4Addr::from(bits).into()
175}
176
177fn ipv6_mask(subnet_bits: u32) -> IpAddr {
179 let bits = !0u128 << (128 - subnet_bits);
180 Ipv6Addr::from(bits).into()
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186 use crate::value;
187
188 test_function![
189 ip_subnet => IpSubnet;
190
191 ipv4 {
192 args: func_args![value: "192.168.10.23",
193 subnet: "255.255.0.0"],
194 want: Ok(value!("192.168.0.0")),
195 tdef: TypeDef::bytes().fallible(),
196 }
197
198 ipv6 {
199 args: func_args![value: "2404:6800:4003:c02::64",
200 subnet: "ff00::"],
201 want: Ok(value!("2400::")),
202 tdef: TypeDef::bytes().fallible(),
203 }
204
205 ipv4_subnet {
206 args: func_args![value: "192.168.10.23",
207 subnet: "/16"],
208 want: Ok(value!("192.168.0.0")),
209 tdef: TypeDef::bytes().fallible(),
210 }
211
212 ipv4_smaller_subnet {
213 args: func_args![value: "192.168.10.23",
214 subnet: "/12"],
215 want: Ok(value!("192.160.0.0")),
216 tdef: TypeDef::bytes().fallible(),
217 }
218
219 ipv6_subnet {
220 args: func_args![value: "2404:6800:4003:c02::64",
221 subnet: "/32"],
222 want: Ok(value!("2404:6800::")),
223 tdef: TypeDef::bytes().fallible(),
224 }
225 ];
226}