1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//! Error types for MaxMind DB operations.
use std::fmt::Display;
use std::io;
use ipnetwork::IpNetworkError;
use serde::de;
use thiserror::Error;
/// Error returned by MaxMind DB operations.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum MaxMindDbError {
/// The database file is invalid or corrupted.
#[error("{}", format_invalid_database(.message, .offset))]
InvalidDatabase {
/// Description of what is invalid.
message: String,
/// Byte offset where the error was detected. Reader operations report
/// an absolute database-file offset; decoding a standalone section
/// reports an offset relative to that input.
offset: Option<usize>,
},
/// An I/O error occurred while reading the database.
#[error("i/o error: {0}")]
Io(
#[from]
#[source]
io::Error,
),
/// Memory mapping failed.
#[cfg(feature = "mmap")]
#[error("memory map error: {0}")]
Mmap(#[source] io::Error),
/// Error decoding data from the database.
#[error(
"{}",
format_contextual_error("decoding error", .message, .offset, .path.as_deref())
)]
Decoding {
/// Description of the decoding error.
message: String,
/// Byte offset relative to the section being decoded: the data section
/// for records, or the metadata value after its marker for metadata.
offset: Option<usize>,
/// JSON-pointer-like path to the field (e.g., "/city/names/en").
path: Option<String>,
},
/// Decoding or verification stopped because it exceeded an expansion or
/// work safety limit.
///
/// This does not necessarily mean that the database is structurally
/// invalid. Schema-specific limits reported by a custom Serde visitor use
/// [`MaxMindDbError::Decoding`] instead. Applications may choose a narrower
/// schema or reject the database as untrusted input.
#[error(
"{}",
format_contextual_error("resource limit exceeded", .message, .offset, .path.as_deref())
)]
ResourceLimit {
/// Description of the limit that was exceeded.
message: String,
/// Byte offset relative to the section being decoded: the data section
/// for records, or the metadata value after its marker for metadata.
offset: Option<usize>,
/// JSON-pointer-like path to the field (e.g., "/subdivisions").
path: Option<String>,
},
/// The provided network/CIDR is invalid.
#[error("invalid network: {0}")]
InvalidNetwork(
#[from]
#[source]
IpNetworkError,
),
/// The provided input is invalid for this operation.
#[error("invalid input: {message}")]
InvalidInput {
/// Description of what is invalid about the input.
message: String,
},
}
fn format_invalid_database(message: &str, offset: &Option<usize>) -> String {
match offset {
Some(off) => format!("invalid database at offset {off}: {message}"),
None => format!("invalid database: {message}"),
}
}
fn format_contextual_error(
prefix: &str,
message: &str,
offset: &Option<usize>,
path: Option<&str>,
) -> String {
match (offset, path) {
(Some(off), Some(p)) => format!("{prefix} at offset {off} (path: {p}): {message}"),
(Some(off), None) => format!("{prefix} at offset {off}: {message}"),
(None, Some(p)) => format!("{prefix} (path: {p}): {message}"),
(None, None) => format!("{prefix}: {message}"),
}
}
impl MaxMindDbError {
/// Creates an InvalidDatabase error with just a message.
pub fn invalid_database(message: impl Into<String>) -> Self {
MaxMindDbError::InvalidDatabase {
message: message.into(),
offset: None,
}
}
/// Creates an InvalidDatabase error with message and offset.
pub fn invalid_database_at(message: impl Into<String>, offset: usize) -> Self {
MaxMindDbError::InvalidDatabase {
message: message.into(),
offset: Some(offset),
}
}
/// Creates a Decoding error with just a message.
pub fn decoding(message: impl Into<String>) -> Self {
MaxMindDbError::Decoding {
message: message.into(),
offset: None,
path: None,
}
}
/// Creates a Decoding error with message and offset.
pub fn decoding_at(message: impl Into<String>, offset: usize) -> Self {
MaxMindDbError::Decoding {
message: message.into(),
offset: Some(offset),
path: None,
}
}
/// Creates a Decoding error with message, offset, and path.
pub fn decoding_at_path(
message: impl Into<String>,
offset: usize,
path: impl Into<String>,
) -> Self {
MaxMindDbError::Decoding {
message: message.into(),
offset: Some(offset),
path: Some(path.into()),
}
}
/// Creates a ResourceLimit error with a message and offset.
pub fn resource_limit_at(message: impl Into<String>, offset: usize) -> Self {
MaxMindDbError::ResourceLimit {
message: message.into(),
offset: Some(offset),
path: None,
}
}
/// Translate a decoder-originated invalid-database offset from a section
/// into the containing database. Other error variants intentionally retain
/// their documented section-relative offsets.
pub(crate) fn with_invalid_database_offset_base(self, base: usize) -> Self {
match self {
MaxMindDbError::InvalidDatabase {
message,
offset: Some(offset),
} => MaxMindDbError::InvalidDatabase {
message,
offset: offset.checked_add(base),
},
_ => self,
}
}
/// Creates an InvalidInput error.
pub fn invalid_input(message: impl Into<String>) -> Self {
MaxMindDbError::InvalidInput {
message: message.into(),
}
}
}
impl de::Error for MaxMindDbError {
fn custom<T: Display>(msg: T) -> Self {
MaxMindDbError::decoding(msg.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Error, ErrorKind};
#[test]
fn test_error_display() {
// Error without offset
assert_eq!(
format!(
"{}",
MaxMindDbError::invalid_database("something went wrong")
),
"invalid database: something went wrong".to_owned(),
);
// Error with offset
assert_eq!(
format!(
"{}",
MaxMindDbError::invalid_database_at("something went wrong", 42)
),
"invalid database at offset 42: something went wrong".to_owned(),
);
let io_err = Error::new(ErrorKind::NotFound, "file not found");
assert_eq!(
format!("{}", MaxMindDbError::from(io_err)),
"i/o error: file not found".to_owned(),
);
#[cfg(feature = "mmap")]
{
let mmap_io_err = Error::new(ErrorKind::PermissionDenied, "mmap failed");
assert_eq!(
format!("{}", MaxMindDbError::Mmap(mmap_io_err)),
"memory map error: mmap failed".to_owned(),
);
}
// Decoding error without offset
assert_eq!(
format!("{}", MaxMindDbError::decoding("unexpected type")),
"decoding error: unexpected type".to_owned(),
);
// Decoding error with offset
assert_eq!(
format!("{}", MaxMindDbError::decoding_at("unexpected type", 100)),
"decoding error at offset 100: unexpected type".to_owned(),
);
// Decoding error with offset and path
assert_eq!(
format!(
"{}",
MaxMindDbError::decoding_at_path("unexpected type", 100, "/city/names/en")
),
"decoding error at offset 100 (path: /city/names/en): unexpected type".to_owned(),
);
assert_eq!(
format!(
"{}",
MaxMindDbError::resource_limit_at("too many values", 100)
),
"resource limit exceeded at offset 100: too many values".to_owned(),
);
let net_err = IpNetworkError::InvalidPrefix;
assert_eq!(
format!("{}", MaxMindDbError::from(net_err)),
"invalid network: invalid prefix".to_owned(),
);
// InvalidInput error
assert_eq!(
format!("{}", MaxMindDbError::invalid_input("bad address")),
"invalid input: bad address".to_owned(),
);
}
}