1use std::fmt;
10use std::path::PathBuf;
11
12use crate::closed_enum::closed_enum;
13use crate::formats::detect::ExtractOnlyFormat;
14
15closed_enum! {
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30 #[non_exhaustive]
31 pub enum ConfigSetting {
32 MaxFileSize => "max_file_size",
34 MaxTotalSize => "max_total_size",
36 MaxFileCount => "max_file_count",
38 MaxPathDepth => "max_path_depth",
40 MaxCompressionRatio => "max_compression_ratio",
42 MaxSolidCompressionRatio => "max_solid_compression_ratio",
44 MaxSolidBlockMemory => "max_solid_block_memory",
46 MaxTarMetadataBytes => "max_tar_metadata_bytes",
48 MaxDecoderMemory => "max_decoder_memory",
50 DecompressionBudget => "decompression_budget",
52 AllowedExtension => "allowed_extension",
54 BannedPathComponent => "banned_path_component",
56 OutputPath => "output_path",
58 SourcePaths => "source_paths",
60 StripPrefix => "strip_prefix",
62 CreationFormat => "creation_format",
64 AtomicExtraction => "atomic_extraction",
66 ZipOutputWriter => "zip_output_writer",
68 MaxBytes => "max_bytes",
70 ParallelDecodeMemory => "parallel_decode_memory",
73 ExcludePattern => "exclude_pattern",
75 ZipConsistency => "zip_consistency",
77 PathModel => "path_model",
79 ArchiveFormat => "archive_format",
81 DecodeReuse => "decode_reuse",
83 DecodeReuseLimit => "decode_reuse_limit",
85 SkipKind => "skip_kind",
87 Durability => "durability",
89 }
90}
91
92impl ConfigSetting {
93 #[must_use]
106 pub fn describe(self, problem: &ConfigProblem) -> String {
107 match problem {
108 ConfigProblem::NoneProvided => format!("no {} provided", self.label()),
109 ConfigProblem::NotCreatable { .. } => problem.to_string(),
110 other => format!("{} {other}", self.label()),
111 }
112 }
113
114 #[must_use]
116 pub const fn label(self) -> &'static str {
117 match self {
118 Self::DecompressionBudget => "decompression budget",
119 Self::AllowedExtension => "allowed extension",
120 Self::BannedPathComponent => "banned path component",
121 Self::OutputPath => "output path",
122 Self::SourcePaths => "source paths",
123 Self::CreationFormat => "creation format",
124 Self::AtomicExtraction => "atomic extraction",
125 Self::ZipOutputWriter => "ZIP output writer",
126 Self::ParallelDecodeMemory => "parallel decode memory",
127 Self::ExcludePattern => "exclude pattern",
128 Self::ZipConsistency => "zip consistency",
129 Self::PathModel => "path model",
130 Self::ArchiveFormat => "archive format",
131 Self::DecodeReuse => "decode reuse",
132 Self::DecodeReuseLimit => "decode reuse limit",
133 Self::SkipKind => "skip kind",
134 Self::MaxFileSize
135 | Self::MaxTotalSize
136 | Self::MaxFileCount
137 | Self::MaxPathDepth
138 | Self::MaxCompressionRatio
139 | Self::MaxSolidCompressionRatio
140 | Self::MaxSolidBlockMemory
141 | Self::MaxTarMetadataBytes
142 | Self::MaxDecoderMemory
143 | Self::StripPrefix
144 | Self::Durability
145 | Self::MaxBytes => self.as_str(),
146 }
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum ConfigProblem {
162 Zero,
164 Negative,
166 NotFinite,
168 NotWholeNumber,
170 TooLarge {
172 max: u64,
174 },
175 NotSet,
177 NoneProvided,
179 NoParent,
181 NotSupported,
183 CannotTargetSink,
185 RemovesWholeName {
187 path: PathBuf,
189 },
190 NotAtStart,
192 Empty,
194 BlankOrControl,
196 PaddedWithBlank,
198 ContainsSeparator,
200 InnerDot,
202 DotEntry,
204 NotOneOf {
206 allowed: &'static [&'static str],
208 },
209 NotCreatable {
211 format: ExtractOnlyFormat,
213 },
214 TooLong {
216 max: usize,
218 got: usize,
220 },
221 ContainsNul,
223 ExcludePatternRefused {
225 pattern: String,
227 reason: ExcludeRefusal,
229 },
230}
231
232closed_enum! {
233 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
243 #[non_exhaustive]
244 pub enum ExcludeRefusal {
245 Empty => "empty",
247 TooLong => "too_long",
249 ContainsNul => "contains_nul",
251 DotEntry => "dot_entry",
253 Absolute => "absolute",
255 UnsupportedWildcard => "unsupported_wildcard",
257 WildcardWithSeparator => "wildcard_with_separator",
259 GlobMetacharacter => "glob_metacharacter",
262 PaddedWithBlank => "padded_with_blank",
264 ContainsComma => "contains_comma",
266 }
267}
268
269impl ExcludeRefusal {
270 #[must_use]
272 pub const fn explanation(self) -> &'static str {
273 match self {
274 Self::Empty => "is empty",
275 Self::TooLong => "is longer than the maximum entry length",
276 Self::ContainsNul => "contains a null byte",
277 Self::DotEntry => "has a `.` or `..` component",
278 Self::Absolute => {
279 "is an absolute path; patterns match archive paths, which are relative"
280 }
281 Self::UnsupportedWildcard => {
282 "uses an unsupported `*` shape; only `name`, `name*` and `*name` are supported"
283 }
284 Self::WildcardWithSeparator => {
285 "combines `*` with a path separator (for `build/*` write `build`)"
286 }
287 Self::GlobMetacharacter => {
288 "contains `?`, `[`, `]`, `{`, `}` or `!`, which are not glob syntax here and would match literally"
289 }
290 Self::PaddedWithBlank => "starts or ends with whitespace",
291 Self::ContainsComma => "contains a comma; give one pattern per option",
292 }
293 }
294}
295
296impl fmt::Display for ConfigProblem {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 match self {
299 Self::Zero => f.write_str("must not be zero"),
300 Self::Negative => f.write_str("must not be negative"),
301 Self::NotOneOf { allowed } => {
302 write!(
303 f,
304 "is not one of the allowed values: {}",
305 allowed.join(", ")
306 )
307 }
308 Self::NotCreatable { format } => {
309 write!(
310 f,
311 "{} archive creation is not supported",
312 format.extension()
313 )
314 }
315 Self::NotFinite => f.write_str("must be a finite number"),
316 Self::NotWholeNumber => f.write_str("must be a whole number"),
317 Self::TooLarge { max } => write!(f, "must not exceed {max}"),
318 Self::NotSet => f.write_str("not set"),
319 Self::NoneProvided => f.write_str("none provided"),
320 Self::NoParent => f.write_str("has no parent"),
321 Self::NotSupported => f.write_str("is not supported"),
322 Self::CannotTargetSink => f.write_str("renames a directory and cannot target a sink"),
323 Self::RemovesWholeName { path } => {
324 write!(f, "removes the whole name of {}", path.display())
325 }
326 Self::NotAtStart => f.write_str("must be positioned at offset 0"),
327 Self::Empty => f.write_str("must not be empty"),
328 Self::BlankOrControl => {
329 f.write_str("must not contain whitespace or control characters")
330 }
331 Self::PaddedWithBlank => {
332 f.write_str("must not start or end with whitespace or control characters")
333 }
334 Self::ContainsSeparator => f.write_str("must not contain a path separator"),
335 Self::InnerDot => f.write_str(
336 "must be a single extension without an inner dot (use `gz`, not `tar.gz`)",
337 ),
338 Self::DotEntry => f.write_str("must not be `.` or `..`"),
339 Self::TooLong { max, got } => {
340 write!(f, "exceeds maximum length of {max} bytes (got {got} bytes)")
341 }
342 Self::ContainsNul => f.write_str("contains null bytes - potential security issue"),
343 Self::ExcludePatternRefused { pattern, reason } => {
344 write!(f, "{pattern:?} {}", reason.explanation())
345 }
346 }
347 }
348}
349
350pub(crate) fn message(setting: ConfigSetting, problem: &ConfigProblem) -> String {
351 setting.describe(problem)
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 #[test]
359 fn the_ffi_kind_names_the_setting() {
360 let err = crate::ArchiveError::InvalidConfiguration {
361 setting: ConfigSetting::MaxFileCount,
362 problem: ConfigProblem::Zero,
363 };
364 assert_eq!(err.ffi_kind().setting(), Some(ConfigSetting::MaxFileCount));
365 assert_eq!(
366 crate::ArchiveError::from(crate::Malformation::PackSizesOverflow)
367 .ffi_kind()
368 .setting(),
369 None
370 );
371 }
372
373 #[test]
374 fn a_host_path_keeps_its_native_spelling() {
375 let problem = ConfigProblem::RemovesWholeName {
376 path: PathBuf::from("C:\\src\\a"),
377 };
378 let text = problem.to_string();
379 assert!(text.ends_with("C:\\src\\a"), "{text}");
380 }
381
382 #[test]
383 fn messages_keep_their_established_text() {
384 let cases = [
385 (
386 ConfigSetting::MaxFileSize,
387 ConfigProblem::Zero,
388 "max_file_size must not be zero",
389 ),
390 (
391 ConfigSetting::MaxCompressionRatio,
392 ConfigProblem::NotFinite,
393 "max_compression_ratio must be a finite number",
394 ),
395 (
396 ConfigSetting::DecompressionBudget,
397 ConfigProblem::Zero,
398 "decompression budget must not be zero",
399 ),
400 (
401 ConfigSetting::SourcePaths,
402 ConfigProblem::NoneProvided,
403 "no source paths provided",
404 ),
405 (
406 ConfigSetting::OutputPath,
407 ConfigProblem::NoParent,
408 "output path has no parent",
409 ),
410 (
411 ConfigSetting::CreationFormat,
412 ConfigProblem::NotCreatable {
413 format: ExtractOnlyFormat::SevenZ,
414 },
415 "7z archive creation is not supported",
416 ),
417 (
418 ConfigSetting::AtomicExtraction,
419 ConfigProblem::CannotTargetSink,
420 "atomic extraction renames a directory and cannot target a sink",
421 ),
422 (
423 ConfigSetting::DecodeReuse,
424 ConfigProblem::NotOneOf {
425 allowed: crate::DecodeReuseKind::NAMES,
426 },
427 "decode reuse is not one of the allowed values: off, memory, temp_file",
428 ),
429 (
430 ConfigSetting::StripPrefix,
431 ConfigProblem::RemovesWholeName { path: "a".into() },
432 "strip_prefix removes the whole name of a",
433 ),
434 (
435 ConfigSetting::ZipOutputWriter,
436 ConfigProblem::NotAtStart,
437 "ZIP output writer must be positioned at offset 0",
438 ),
439 (
440 ConfigSetting::AllowedExtension,
441 ConfigProblem::TooLong { max: 4, got: 5 },
442 "allowed extension exceeds maximum length of 4 bytes (got 5 bytes)",
443 ),
444 ];
445 for (setting, problem, text) in cases {
446 assert_eq!(message(setting, &problem), text);
447 }
448 }
449}