maxminddb/within.rs
1//! Network iteration types.
2
3use std::cmp::Ordering;
4use std::net::{IpAddr, Ipv6Addr};
5
6use crate::decoder;
7use crate::error::MaxMindDbError;
8use crate::reader::{search_tree_too_deep_error, Reader};
9use crate::result::{LookupResult, LookupSource, NetworkKind};
10
11/// Options for network iteration.
12///
13/// Controls which networks are yielded when iterating over the database
14/// with [`Reader::within()`] or [`Reader::networks()`].
15///
16/// # Example
17///
18/// ```
19/// use maxminddb::WithinOptions;
20///
21/// // Default options (skip aliases, skip networks without data, include empty values)
22/// let opts = WithinOptions::default();
23///
24/// // Include aliased networks (IPv4 networks via IPv6 aliases)
25/// let opts = WithinOptions::default().include_aliased_networks();
26///
27/// // Skip empty values and include networks without data
28/// let opts = WithinOptions::default()
29/// .skip_empty_values()
30/// .include_networks_without_data();
31/// ```
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
33pub struct WithinOptions {
34 /// Include IPv4 networks multiple times when accessed via IPv6 aliases.
35 include_aliased_networks: bool,
36 /// Include networks that have no associated data record.
37 include_networks_without_data: bool,
38 /// Skip networks whose data is an empty map or empty array.
39 skip_empty_values: bool,
40}
41
42impl WithinOptions {
43 /// Include IPv4 networks multiple times when accessed via IPv6 aliases.
44 ///
45 /// In IPv6 databases, IPv4 networks are stored at `::0/96`. However, the
46 /// same data is accessible through several IPv6 prefixes (e.g.,
47 /// `::ffff:0:0/96` for IPv4-mapped IPv6). By default, these aliases are
48 /// skipped to avoid yielding the same network multiple times.
49 ///
50 /// When enabled, the iterator will yield these aliased networks.
51 #[must_use]
52 pub fn include_aliased_networks(mut self) -> Self {
53 self.include_aliased_networks = true;
54 self
55 }
56
57 /// Include networks that have no associated data record.
58 ///
59 /// Some tree nodes point to "no data" (the node_count sentinel). By default
60 /// these are skipped. When enabled, these networks are yielded and
61 /// [`LookupResult::has_data()`] returns `false` for them.
62 #[must_use]
63 pub fn include_networks_without_data(mut self) -> Self {
64 self.include_networks_without_data = true;
65 self
66 }
67
68 /// Skip networks whose data is an empty map or empty array.
69 ///
70 /// Some databases store empty maps `{}` or empty arrays `[]` for records
71 /// without meaningful data. This option filters them out.
72 #[must_use]
73 pub fn skip_empty_values(mut self) -> Self {
74 self.skip_empty_values = true;
75 self
76 }
77}
78
79#[derive(Debug)]
80pub(crate) struct WithinNode {
81 pub(crate) node: usize,
82 pub(crate) ip_int: IpInt,
83 pub(crate) prefix_len: usize,
84}
85
86/// Iterator over database networks matching a CIDR range.
87///
88/// Created by [`Reader::within()`](crate::Reader::within) or
89/// [`Reader::networks()`](crate::Reader::networks). Yields
90/// [`LookupResult`] for matching networks, subject to [`WithinOptions`].
91/// Matching uses the database's search-tree address space. Results are not
92/// clipped to the requested range and can include an enclosing database network.
93/// Returned networks can use a different address family than the requested CIDR.
94/// See [`Reader::within()`](crate::Reader::within) for IPv4/IPv6 representation rules.
95///
96/// Networks are yielded in depth-first order through the search tree.
97/// Use [`LookupResult::decode()`](crate::LookupResult::decode) to
98/// deserialize the data for each result.
99///
100/// If the search tree contains a cycle, or any branch is deeper than the
101/// address, the iterator yields one [`MaxMindDbError::InvalidDatabase`] error
102/// and then ends, so later networks are not returned.
103///
104/// # Example
105///
106/// ```
107/// use maxminddb::{Reader, WithinOptions, geoip2};
108///
109/// let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
110/// for result in reader.within("89.160.20.0/24".parse().unwrap(), Default::default()).unwrap() {
111/// let lookup = result.unwrap();
112/// if let Some(city) = lookup.decode::<geoip2::City>().unwrap() {
113/// println!("{}: {:?}", lookup.network().unwrap(), city.city.names.english);
114/// }
115/// }
116/// ```
117#[derive(Debug)]
118pub struct Within<'de, S: AsRef<[u8]>> {
119 pub(crate) reader: &'de Reader<S>,
120 pub(crate) node_count: usize,
121 pub(crate) has_ipv4_subtree: bool,
122 pub(crate) stack: Vec<WithinNode>,
123 pub(crate) options: WithinOptions,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub(crate) enum IpInt {
128 V4(u32),
129 V6(u128),
130}
131
132impl IpInt {
133 pub(crate) fn new(ip_addr: IpAddr) -> Self {
134 match ip_addr {
135 IpAddr::V4(v4) => IpInt::V4(v4.into()),
136 IpAddr::V6(v6) => IpInt::V6(v6.into()),
137 }
138 }
139
140 #[inline(always)]
141 pub(crate) fn get_bit(&self, index: usize) -> bool {
142 match self {
143 IpInt::V4(ip) => (ip >> (31 - index)) & 1 == 1,
144 IpInt::V6(ip) => (ip >> (127 - index)) & 1 == 1,
145 }
146 }
147
148 #[inline(always)]
149 pub(crate) fn set_bit(&mut self, index: usize) {
150 match self {
151 IpInt::V4(ip) => *ip |= 1 << (31 - index),
152 IpInt::V6(ip) => *ip |= 1 << (127 - index),
153 }
154 }
155
156 pub(crate) fn bit_count(&self) -> usize {
157 match self {
158 IpInt::V4(_) => 32,
159 IpInt::V6(_) => 128,
160 }
161 }
162
163 pub(crate) fn is_ipv4_in_ipv6(&self) -> bool {
164 match self {
165 IpInt::V4(_) => false,
166 IpInt::V6(ip) => *ip <= 0xFFFFFFFF,
167 }
168 }
169}
170
171impl<'de, S: AsRef<[u8]>> Iterator for Within<'de, S> {
172 type Item = Result<LookupResult<'de, S>, MaxMindDbError>;
173
174 fn next(&mut self) -> Option<Self::Item> {
175 while let Some(current) = self.stack.pop() {
176 let bit_count = current.ip_int.bit_count();
177
178 // Only internal IPv4 subtrees have aliases. Terminal records can be shared.
179 if !self.options.include_aliased_networks
180 && self.has_ipv4_subtree
181 && self.reader.ipv4_start != 0
182 && current.node == self.reader.ipv4_start
183 && bit_count == 128
184 && !current.ip_int.is_ipv4_in_ipv6()
185 {
186 continue;
187 }
188
189 match current.node.cmp(&self.node_count) {
190 Ordering::Greater => {
191 // This is a data node, emit it and we're done (until the following next call)
192 // Resolve the pointer to a data offset
193 let data_offset = match self.reader.resolve_data_pointer(current.node) {
194 Ok(offset) => offset,
195 Err(e) => return Some(Err(e)),
196 };
197
198 // Check if we should skip empty values
199 if self.options.skip_empty_values {
200 match self.is_empty_value_at(data_offset) {
201 Ok(true) => continue, // Skip empty value
202 Ok(false) => {} // Not empty, proceed
203 Err(e) => return Some(Err(e)),
204 }
205 }
206
207 let network_kind = self.network_kind(¤t);
208 let ip_addr = network_ip_addr(network_kind, current.ip_int);
209
210 return Some(Ok(LookupResult::new_found(
211 self.reader,
212 data_offset,
213 current.prefix_len as u8,
214 ip_addr,
215 LookupSource::Iter,
216 network_kind,
217 )));
218 }
219 Ordering::Equal => {
220 // Dead end (no data) - include if option is set
221 if self.options.include_networks_without_data {
222 let network_kind = self.network_kind(¤t);
223 let ip_addr = network_ip_addr(network_kind, current.ip_int);
224 return Some(Ok(LookupResult::new_not_found(
225 self.reader,
226 current.prefix_len as u8,
227 ip_addr,
228 LookupSource::Iter,
229 network_kind,
230 )));
231 }
232 // Otherwise skip (current behavior)
233 }
234 Ordering::Less => {
235 if current.prefix_len >= bit_count {
236 // A cyclic tree can repeat this for every remaining
237 // network, up to 2^128 times, so end the iteration.
238 self.stack.clear();
239 return Some(Err(search_tree_too_deep_error()));
240 }
241 // In order traversal of our children
242 // right/1-bit
243 let mut right_ip_int = current.ip_int;
244
245 if current.prefix_len < bit_count {
246 right_ip_int.set_bit(current.prefix_len);
247 }
248
249 self.push_child(current.node, 1, right_ip_int, current.prefix_len + 1);
250 // left/0-bit
251 self.push_child(current.node, 0, current.ip_int, current.prefix_len + 1);
252 }
253 }
254 }
255 None
256 }
257}
258
259impl<'de, S: AsRef<[u8]>> Within<'de, S> {
260 #[inline(always)]
261 fn network_kind(&self, node: &WithinNode) -> NetworkKind {
262 match node.ip_int {
263 IpInt::V4(_) if self.reader.metadata().ip_version == 6 && !self.has_ipv4_subtree => {
264 NetworkKind::V6
265 }
266 IpInt::V4(_) => NetworkKind::V4,
267 IpInt::V6(_)
268 if node.ip_int.is_ipv4_in_ipv6()
269 && self.has_ipv4_subtree
270 && node.prefix_len >= self.reader.ipv4_start_bit_depth =>
271 {
272 NetworkKind::V4InV6Subtree
273 }
274 IpInt::V6(_) => NetworkKind::V6,
275 }
276 }
277
278 fn push_child(
279 &mut self,
280 parent_node: usize,
281 direction: usize,
282 ip_int: IpInt,
283 prefix_len: usize,
284 ) {
285 let node = self.reader.read_node(parent_node, direction);
286 self.stack.push(WithinNode {
287 node,
288 ip_int,
289 prefix_len,
290 });
291 }
292
293 /// Check if the value at the given data offset is an empty map or array.
294 fn is_empty_value_at(&self, data_offset: usize) -> Result<bool, MaxMindDbError> {
295 let mut dec = decoder::Decoder::new(self.reader.data_section()?, data_offset);
296 let (size, type_num) = dec
297 .peek_type()
298 .map_err(|error| error.with_invalid_database_offset_base(self.reader.pointer_base))?;
299 match type_num {
300 decoder::TYPE_MAP | decoder::TYPE_ARRAY => Ok(size == 0),
301 _ => Ok(false), // Non-container types are never "empty"
302 }
303 }
304}
305
306#[inline(always)]
307fn network_ip_addr(network_kind: NetworkKind, ip_int: IpInt) -> IpAddr {
308 let ip_addr = ip_int_to_addr(&ip_int);
309 match (network_kind, ip_int, ip_addr) {
310 // Low IPv6 tree keys are normally formatted as IPv4 addresses for IPv4
311 // subtree records. When the record is really IPv6, preserve the low
312 // IPv6 bits instead of collapsing the network to ::.
313 (NetworkKind::V6, IpInt::V6(ip), IpAddr::V4(_)) => IpAddr::V6(ip.into()),
314 // Defensive fallback for IPv4 CIDR iteration in IPv6 databases without
315 // an IPv4 subtree. Reader::within() should seed those as IpInt::V6(0).
316 (NetworkKind::V6, IpInt::V4(_), IpAddr::V4(_)) => IpAddr::V6(Ipv6Addr::UNSPECIFIED),
317 (_, _, ip_addr) => ip_addr,
318 }
319}
320
321/// Convert IpInt to IpAddr
322#[inline(always)]
323pub(crate) fn ip_int_to_addr(ip_int: &IpInt) -> IpAddr {
324 match ip_int {
325 IpInt::V4(ip) => IpAddr::V4((*ip).into()),
326 IpInt::V6(ip) => {
327 // Check if this is an IPv4-mapped IPv6 address.
328 if *ip <= 0xFFFFFFFF {
329 IpAddr::V4((*ip as u32).into())
330 } else {
331 IpAddr::V6((*ip).into())
332 }
333 }
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
340
341 use crate::result::NetworkKind;
342
343 use super::{network_ip_addr, IpInt};
344
345 #[test]
346 fn network_ip_addr_preserves_low_ipv6_bits() {
347 assert_eq!(
348 network_ip_addr(NetworkKind::V6, IpInt::V6(1)),
349 IpAddr::V6(Ipv6Addr::from(1_u128))
350 );
351 }
352
353 #[test]
354 fn network_ip_addr_formats_ipv4_subtree_records_as_ipv4() {
355 assert_eq!(
356 network_ip_addr(NetworkKind::V4InV6Subtree, IpInt::V6(1)),
357 IpAddr::V4(Ipv4Addr::from(1_u32))
358 );
359 }
360}