1use crate::config::envelope::UnknownDetectionEnvelope;
43use crate::config::{
44 UnknownOsDetection, UnknownScanEffort, UnknownScanPace, UnknownServiceDetection,
45};
46use crate::cve::{AdvisoriesError, CatalogueError};
47use crate::detect::bundle::BundleError;
48use crate::detect::compute::{CapError, LoadError, ReplayError};
49use crate::detect::corpus::DetectionError;
50use crate::detect::flow::ParseError as FlowParseError;
51use crate::evasion::EvasionError;
52use crate::export::ExportError;
53#[cfg(feature = "fetch")]
54use crate::fetch::{DeriveError, FetchError, InvalidResource, NetworkFailure, VerificationFailure};
55use crate::fingerprint::os::{InvalidRule, RuleError};
56use crate::fingerprint::{DefinitionError, InvalidDefinition};
57use crate::import::ImportError;
58#[cfg(feature = "import-kev")]
59use crate::import::kev::KevError;
60#[cfg(feature = "import-nvd")]
61use crate::import::nvd::NvdError;
62#[cfg(feature = "journal-format")]
63use crate::journal::format::JournalError;
64#[cfg(feature = "journal-format")]
65use crate::journal::lock::LockRefused;
66#[cfg(feature = "journal-format")]
67use crate::journal::manifest::{OptionChanged, PlanChanged};
68#[cfg(feature = "journal-format")]
69use crate::journal::store::OpenError;
70use crate::model::finding::{FindingError, VersionParseError};
71use crate::model::ip::range::IpError;
72use crate::model::ip::scoped::ScopedIpError;
73use crate::model::ip::set::IpSetError;
74use crate::model::mac::MacAddrParseError;
75use crate::model::parse::ip::IpParseError;
76use crate::model::parse::target::TargetParseError;
77use crate::model::port::set::PortSetParseError;
78use crate::model::target::TargetError;
79use crate::model::technique::{UnknownSctpTechnique, UnknownTechnique};
80use crate::model::tls::UnknownTlsVersion;
81use crate::protocols::error::PacketError;
82use crate::resolve::LinkError;
83use crate::scanner::ScanError;
84use crate::scanner::rdns::ResolverError;
85use crate::scanner::strategy::StrategyError;
86use crate::signature::SignatureError;
87use crate::transport::capture::{CaptureError, LibraryError};
88use crate::transport::channel::ChannelError;
89#[cfg(feature = "packet-exchange")]
90use crate::transport::exchange::ExchangeError;
91use crate::transport::probe::{SendError, TransportError, UnknownSendMode};
92use crate::transport::raw::RawSocketError;
93
94#[cfg(feature = "import-request")]
95use crate::import::request::RequestError;
96#[cfg(feature = "import-settings")]
97use crate::import::settings::SettingsError;
98
99pub trait Coded {
104 fn code(&self) -> &'static str;
109}
110
111impl Coded for ScanError {
112 fn code(&self) -> &'static str {
113 match self {
114 ScanError::WrongPhase => "scan.wrong_phase",
115 #[cfg(feature = "journal-format")]
116 ScanError::PlanChanged(changed) => changed.code(),
117 #[cfg(feature = "journal-format")]
118 ScanError::OptionChanged(changed) => changed.code(),
119 ScanError::Evasion(evasion) => evasion.code(),
120 ScanError::TooFewDescriptors { .. } => "scan.too_few_descriptors",
121 ScanError::TaskFailed { panicked: true, .. } => "scan.task_panicked",
124 ScanError::TaskFailed { .. } => "scan.task_failed",
125 }
126 }
127}
128
129#[cfg(feature = "journal-format")]
130impl Coded for PlanChanged {
131 fn code(&self) -> &'static str {
132 "journal.plan_changed"
133 }
134}
135
136#[cfg(feature = "journal-format")]
137impl Coded for OptionChanged {
138 fn code(&self) -> &'static str {
139 "journal.option_changed"
140 }
141}
142
143impl Coded for EvasionError {
144 fn code(&self) -> &'static str {
145 match self {
146 EvasionError::FragmentTooSmall { .. } => "evasion.fragment_too_small",
147 EvasionError::HopLimitZero => "evasion.hop_limit_zero",
148 EvasionError::PaddingTooLarge { .. } => "evasion.padding_too_large",
149 EvasionError::SourcePortZero => "evasion.source_port_zero",
150 }
151 }
152}
153
154impl Coded for ExportError {
155 fn code(&self) -> &'static str {
156 match self {
157 ExportError::Io(_) => "export.io",
158 ExportError::Render { .. } => "export.render",
159 }
160 }
161}
162
163#[cfg(feature = "journal-format")]
164impl Coded for JournalError {
165 fn code(&self) -> &'static str {
166 match self {
167 JournalError::Io(_) => "journal.io",
168 JournalError::Malformed { .. } => "journal.malformed",
169 JournalError::NotAJournal => "journal.not_a_journal",
170 JournalError::VersionTooNew { .. } => "journal.version_too_new",
171 }
172 }
173}
174
175#[cfg(feature = "journal-format")]
176impl Coded for OpenError {
177 fn code(&self) -> &'static str {
178 match self {
179 OpenError::Journal(journal) => journal.code(),
180 OpenError::Locked(refused) => refused.code(),
181 OpenError::PlanChanged(changed) => changed.code(),
182 OpenError::WrongPhase { .. } => "journal.wrong_phase",
183 }
184 }
185}
186
187#[cfg(feature = "journal-format")]
188impl Coded for LockRefused {
189 fn code(&self) -> &'static str {
190 match self {
191 LockRefused::Held(_) => "journal.locked",
192 LockRefused::Io(_) => "journal.lock_io",
193 }
194 }
195}
196
197impl Coded for crate::journal::paths::ScanPathError {
198 fn code(&self) -> &'static str {
199 match self {
200 Self::NoRoot => "journal.no_root",
201 Self::NotAnId(_) => "journal.not_an_id",
202 }
203 }
204}
205
206impl Coded for DetectionError {
207 fn code(&self) -> &'static str {
208 match self {
209 DetectionError::Body(_) => "detection.body",
210 DetectionError::Compute(_) => "detection.compute",
211 DetectionError::Flow(_) => "detection.flow",
212 DetectionError::Host(_) => "detection.host",
213 DetectionError::InSource { cause, .. } => cause.code(),
214 DetectionError::Parse(_) => "detection.parse",
215 DetectionError::Pattern(_) => "detection.pattern",
216 DetectionError::Tier(_) => "detection.tier",
217 DetectionError::UnusedBody { .. } => "detection.unused_body",
218 }
219 }
220}
221
222impl Coded for TargetParseError {
223 fn code(&self) -> &'static str {
224 match self {
225 TargetParseError::Address { source, .. } => source.code(),
226 TargetParseError::Ports { source, .. } => source.code(),
227 TargetParseError::Blank(..) => "target.blank",
228 TargetParseError::Empty => "target.empty",
229 TargetParseError::EmptyPorts(_) => "target.empty_ports",
230 TargetParseError::MistypedAddress(_) => "target.mistyped_address",
231 TargetParseError::NoHostLookup(_) => "target.no_host_lookup",
232 TargetParseError::ResolvedToNothing(_) => "target.resolved_to_nothing",
233 TargetParseError::TrailingText(_) => "target.trailing_text",
234 TargetParseError::UnbalancedBracket(_) => "target.unbalanced_bracket",
235 TargetParseError::UnbracketedAddress(_) => "target.unbracketed_address",
236 TargetParseError::UnknownHost(_) => "target.unknown_host",
237 }
238 }
239}
240
241impl Coded for IpParseError {
242 fn code(&self) -> &'static str {
243 match self {
244 IpParseError::EmptySet => "address.empty_set",
245 IpParseError::InvalidPrefix(_) => "address.invalid_prefix",
246 IpParseError::InvalidRange(..) => "address.invalid_range",
247 IpParseError::KeywordUnresolved { .. } => "address.keyword_unresolved",
248 IpParseError::Malformed(_) => "address.malformed",
249 IpParseError::UnknownInterface(_) => "address.unknown_interface",
250 IpParseError::ZoneOnUnscopedTarget(_) => "address.zone_on_unscoped_target",
251 }
252 }
253}
254
255impl Coded for PortSetParseError {
256 fn code(&self) -> &'static str {
257 match self {
258 PortSetParseError::InvalidPort { .. } => "ports.invalid_port",
259 PortSetParseError::InvalidRange { .. } => "ports.invalid_range",
260 PortSetParseError::MalformedSpec(_) => "ports.malformed_spec",
261 PortSetParseError::SpacedRange(_) => "ports.spaced_range",
262 PortSetParseError::ServiceName(_) => "ports.service_name",
263 PortSetParseError::NoPorts => "ports.empty",
264 }
265 }
266}
267
268impl Coded for ImportError {
269 fn code(&self) -> &'static str {
270 match self {
271 ImportError::Io(_) => "import.io",
272 ImportError::LineTooLong { .. } => "import.line_too_long",
273 ImportError::InvalidUtf8 { .. } => "import.invalid_utf8",
274 ImportError::DocumentTooLarge { .. } => "import.document_too_large",
275 ImportError::TooManyHosts { .. } => "import.too_many_hosts",
276 ImportError::TooManyTokens { .. } => "import.too_many_tokens",
277 ImportError::TooManyAddresses { .. } => "import.too_many_addresses",
278 ImportError::Target { source, .. } => source.code(),
279 ImportError::Malformed { .. } => "import.malformed",
280 }
281 }
282}
283
284#[cfg(feature = "import-request")]
285impl Coded for RequestError {
286 fn code(&self) -> &'static str {
287 match self {
288 RequestError::NoTargets => "request.no_targets",
289 RequestError::Ports { .. } => "request.bad_ports",
290 RequestError::Targets(source) => source.code(),
291 }
292 }
293}
294
295#[cfg(feature = "import-settings")]
296impl Coded for SettingsError {
297 fn code(&self) -> &'static str {
298 match self {
299 SettingsError::Io { .. } => "settings.io",
300 SettingsError::Malformed(_) => "settings.malformed",
301 SettingsError::NoPath => "settings.no_path",
302 SettingsError::TooLarge { .. } => "settings.too_large",
303 SettingsError::UnknownProfile { .. } => "settings.unknown_profile",
304 }
305 }
306}
307
308#[cfg(feature = "fetch")]
309impl Coded for FetchError {
310 fn code(&self) -> &'static str {
311 match self {
312 FetchError::Setup(_) => "fetch.setup",
313 FetchError::Cancelled => "fetch.cancelled",
314 FetchError::Network { failure, .. } => match failure {
317 NetworkFailure::Url => "fetch.unparsable_url",
318 NetworkFailure::Connect => "fetch.connect",
319 NetworkFailure::Certificate => "fetch.certificate",
320 NetworkFailure::Tls => "fetch.tls",
321 NetworkFailure::TimedOut => "fetch.timed_out",
322 NetworkFailure::Interrupted => "fetch.interrupted",
323 NetworkFailure::Redirects => "fetch.redirects",
324 NetworkFailure::Other => "fetch.network",
325 },
326 FetchError::Insecure => "fetch.insecure",
327 FetchError::Status { .. } => "fetch.status",
328 FetchError::TooLarge { .. } => "fetch.too_large",
329 FetchError::Verification(failure) => failure.code(),
330 FetchError::Storage { .. } => "fetch.storage",
331 }
332 }
333}
334
335#[cfg(feature = "fetch")]
336impl Coded for VerificationFailure {
337 fn code(&self) -> &'static str {
338 match self {
339 VerificationFailure::DigestMismatch => "fetch.digest_mismatch",
340 VerificationFailure::NoSignature(_) => "fetch.no_signature",
343 VerificationFailure::Signature(signature) => signature.code(),
344 }
345 }
346}
347
348#[cfg(feature = "fetch")]
349impl<E: std::error::Error + 'static> Coded for DeriveError<E> {
350 fn code(&self) -> &'static str {
351 match self {
352 DeriveError::Store(store) => store.code(),
353 DeriveError::NotStored { .. } => "fetch.not_stored",
354 DeriveError::Convert(_) => "fetch.conversion",
356 }
357 }
358}
359
360#[cfg(feature = "fetch")]
361impl Coded for InvalidResource {
362 fn code(&self) -> &'static str {
363 match self {
364 InvalidResource::Id(_) => "fetch.invalid_id",
365 InvalidResource::Url(_) => "fetch.invalid_url",
366 InvalidResource::NoSources(_) => "fetch.no_sources",
367 }
368 }
369}
370
371macro_rules! one_code {
374 ($($error:ty => $code:literal),+ $(,)?) => {
375 $(impl Coded for $error {
376 fn code(&self) -> &'static str {
377 $code
378 }
379 })+
380 };
381}
382
383one_code! {
384 UnknownOsDetection => "config.unknown_os_detection",
385 UnknownScanEffort => "config.unknown_scan_effort",
386 UnknownScanPace => "config.unknown_scan_pace",
387 UnknownServiceDetection => "config.unknown_service_detection",
388 UnknownDetectionEnvelope => "config.unknown_detection_envelope",
389 UnknownTechnique => "config.unknown_tcp_technique",
390 UnknownSctpTechnique => "config.unknown_sctp_technique",
391 UnknownSendMode => "config.unknown_send_mode",
392 UnknownTlsVersion => "config.unknown_tls_version",
393 MacAddrParseError => "mac.malformed",
394 VersionParseError => "finding.malformed_version",
395}
396
397impl Coded for FindingError {
398 fn code(&self) -> &'static str {
399 match self {
400 FindingError::EmptyId => "finding.empty_id",
401 FindingError::EmptyTitle => "finding.empty_title",
402 FindingError::EmptyGroup => "finding.empty_group",
403 FindingError::NoExploitedCve => "finding.no_exploited_cve",
404 }
405 }
406}
407
408impl Coded for IpError {
409 fn code(&self) -> &'static str {
410 match self {
411 IpError::InvalidRange(..) => "range.backwards",
412 IpError::InvalidPrefix(_) => "range.invalid_prefix",
413 IpError::AddrParse(_) => "range.malformed_address",
414 IpError::InvalidFormat(_) => "range.malformed",
415 IpError::PrefixParse(_) => "range.malformed_prefix",
416 }
417 }
418}
419
420impl Coded for IpSetError {
421 fn code(&self) -> &'static str {
422 match self {
423 IpSetError::InvalidTarget(range) => range.code(),
424 }
425 }
426}
427
428impl Coded for ScopedIpError {
429 fn code(&self) -> &'static str {
430 match self {
431 ScopedIpError::NotAnAddress(_) => "scoped_address.not_an_address",
432 ScopedIpError::ZoneOnUnscopedAddress(..) => "scoped_address.zone_on_unscoped",
433 ScopedIpError::EmptyZone => "scoped_address.empty_zone",
434 }
435 }
436}
437
438impl Coded for TargetError {
439 fn code(&self) -> &'static str {
440 match self {
441 TargetError::CapacityOverflow => "target.capacity_overflow",
442 }
443 }
444}
445
446impl Coded for LinkError {
447 fn code(&self) -> &'static str {
448 match self {
449 LinkError::Empty => "link.empty",
450 LinkError::Unknown { .. } => "link.unknown",
451 LinkError::NoLan => "link.no_lan",
452 LinkError::NoLinks => "link.no_links",
453 LinkError::Unreadable { .. } => "link.unreadable",
454 }
455 }
456}
457
458impl Coded for CatalogueError {
459 fn code(&self) -> &'static str {
460 match self {
461 CatalogueError::Io(_) => "catalogue.io",
462 CatalogueError::Malformed(_) => "catalogue.malformed",
463 CatalogueError::ReservedId { .. } => "catalogue.reserved_id",
464 CatalogueError::TooLarge { .. } => "catalogue.too_large",
465 CatalogueError::UnreadableVersion { .. } => "catalogue.unreadable_version",
466 }
467 }
468}
469
470impl Coded for AdvisoriesError {
471 fn code(&self) -> &'static str {
472 match self {
473 AdvisoriesError::NotAdvisories => "advisories.not_advisories",
474 AdvisoriesError::UnsupportedFormat { .. } => "advisories.unsupported_format",
475 AdvisoriesError::TooLarge { .. } => "advisories.too_large",
476 AdvisoriesError::Malformed(_) => "advisories.malformed",
477 }
478 }
479}
480
481#[cfg(feature = "import-kev")]
482impl Coded for KevError {
483 fn code(&self) -> &'static str {
484 match self {
485 KevError::Io(_) => "kev.io",
486 KevError::Malformed(_) => "kev.malformed",
487 KevError::TooLarge { .. } => "kev.too_large",
488 KevError::Rejected(catalogue) => catalogue.code(),
489 }
490 }
491}
492
493#[cfg(feature = "import-nvd")]
494impl Coded for NvdError {
495 fn code(&self) -> &'static str {
496 match self {
497 NvdError::Io(_) => "nvd.io",
498 NvdError::Malformed(_) => "nvd.malformed",
499 NvdError::TooLarge { .. } => "nvd.too_large",
500 NvdError::TooManyEntries { .. } => "nvd.too_many_entries",
501 NvdError::Rejected(catalogue) => catalogue.code(),
502 }
503 }
504}
505
506impl Coded for SignatureError {
507 fn code(&self) -> &'static str {
508 match self {
509 SignatureError::UnreadableKey => "signature.unreadable_key",
510 SignatureError::Malformed(_) => "signature.malformed",
511 SignatureError::UnknownAlgorithm { .. } => "signature.unknown_algorithm",
512 SignatureError::UntrustedKey => "signature.untrusted_key",
513 SignatureError::Altered => "signature.altered",
514 SignatureError::Invalid => "signature.invalid",
515 SignatureError::Io(_) => "signature.io",
516 }
517 }
518}
519
520impl Coded for BundleError {
521 fn code(&self) -> &'static str {
522 match self {
523 BundleError::Signature(signature) => signature.code(),
524 BundleError::Manifest(_) => "bundle.manifest",
525 BundleError::Missing { .. } => "bundle.missing",
526 BundleError::Altered { .. } => "bundle.altered",
527 BundleError::Unnamed { .. } => "bundle.unnamed",
528 BundleError::Duplicate { .. } => "bundle.duplicate",
529 BundleError::TooMany { .. } => "bundle.too_many",
530 }
531 }
532}
533
534impl Coded for FlowParseError {
535 fn code(&self) -> &'static str {
536 match self {
537 FlowParseError::Empty => "flow.empty",
538 FlowParseError::UnexpectedChar(_) => "flow.unexpected_char",
539 FlowParseError::UnterminatedString => "flow.unterminated_string",
540 FlowParseError::IntOverflow(_) => "flow.int_overflow",
541 FlowParseError::Expected(_) => "flow.expected",
542 FlowParseError::Trailing => "flow.trailing",
543 FlowParseError::TooDeep => "flow.too_deep",
544 }
545 }
546}
547
548impl Coded for CapError {
549 fn code(&self) -> &'static str {
550 match self {
551 CapError::ByteBudgetExhausted => "capability.byte_budget_exhausted",
552 CapError::ConnectionBudgetExhausted => "capability.connection_budget_exhausted",
553 CapError::Denied(_) => "capability.denied",
554 CapError::OutOfDescriptors => "capability.out_of_descriptors",
555 CapError::Withheld => "capability.withheld",
556 CapError::TimedOut => "capability.timed_out",
557 CapError::ConnectionRefused => "capability.connection_refused",
558 CapError::Reset => "capability.reset",
559 }
560 }
561}
562
563impl Coded for LoadError {
564 fn code(&self) -> &'static str {
565 match self {
566 LoadError::Compile(_) => "compute.compile",
567 LoadError::UnsupportedBody => "compute.unsupported_body",
568 }
569 }
570}
571
572impl Coded for ReplayError {
573 fn code(&self) -> &'static str {
574 match self {
575 ReplayError::UnknownDetection => "replay.unknown_detection",
576 ReplayError::UnknownTransport(_) => "replay.unknown_transport",
577 ReplayError::GrantFailed => "replay.grant_failed",
578 ReplayError::Instantiate(load) => load.code(),
579 ReplayError::Run(_) => "replay.run",
580 ReplayError::Diverged => "replay.diverged",
581 }
582 }
583}
584
585impl Coded for DefinitionError {
586 fn code(&self) -> &'static str {
587 match self {
588 DefinitionError::Pattern { .. } => "definition.pattern",
589 DefinitionError::VersionGroup { .. } => "definition.version_group",
590 DefinitionError::ProbeProtocol { .. } => "definition.probe_protocol",
591 DefinitionError::GenericProbeNotTcp { .. } => "definition.generic_probe_not_tcp",
592 DefinitionError::UdpProbeSize { .. } => "definition.udp_probe_size",
593 }
594 }
595}
596
597impl Coded for InvalidDefinition {
598 fn code(&self) -> &'static str {
599 self.error.code()
600 }
601}
602
603impl Coded for RuleError {
604 fn code(&self) -> &'static str {
605 match self {
606 RuleError::Unidentified => "rule.unidentified",
607 RuleError::VersionWithoutProduct => "rule.version_without_product",
608 RuleError::Weight(_) => "rule.weight",
609 RuleError::Predicate { .. } => "rule.predicate",
610 RuleError::NoPredicates => "rule.no_predicates",
611 RuleError::ExampleWithoutSeries(_) => "rule.example_without_series",
612 RuleError::ExampleWithoutWindow(_) => "rule.example_without_window",
613 }
614 }
615}
616
617impl Coded for InvalidRule {
618 fn code(&self) -> &'static str {
619 self.error.code()
620 }
621}
622
623impl Coded for PacketError {
624 fn code(&self) -> &'static str {
625 match self {
626 PacketError::TooLong { .. } => "packet.too_long",
627 PacketError::FamilyMismatch { .. } => "packet.family_mismatch",
628 PacketError::WrongFamily { .. } => "packet.wrong_family",
629 PacketError::MtuTooSmall { .. } => "packet.mtu_too_small",
630 PacketError::HeaderHasOptions { .. } => "packet.header_has_options",
631 PacketError::OptionsTooLong { .. } => "packet.options_too_long",
632 PacketError::OptionsMisaligned { .. } => "packet.options_misaligned",
633 PacketError::UnsupportedEtherType(_) => "packet.unsupported_ether_type",
634 PacketError::Unreadable { .. } => "packet.unreadable",
635 PacketError::UnexpectedMessage { .. } => "packet.unexpected_message",
636 PacketError::UnwritableName { .. } => "packet.unwritable_name",
637 PacketError::Truncated { .. } => "packet.truncated",
638 }
639 }
640}
641
642impl Coded for CaptureError {
643 fn code(&self) -> &'static str {
644 match self {
645 CaptureError::NoInterface { .. } => "capture.no_interface",
646 CaptureError::NoReader { .. } => "capture.no_reader",
647 CaptureError::UnsupportedLinkType { .. } => "capture.unsupported_link_type",
648 CaptureError::Filter { .. } => "capture.filter",
649 CaptureError::Open { .. } => "capture.open",
650 CaptureError::Denied { .. } => "capture.denied",
651 CaptureError::OutOfDescriptors { .. } => "capture.out_of_descriptors",
652 }
653 }
654}
655
656impl Coded for LibraryError {
657 fn code(&self) -> &'static str {
658 "capture.library"
659 }
660}
661
662impl Coded for RawSocketError {
663 fn code(&self) -> &'static str {
664 match self {
665 RawSocketError::Open { .. } => "raw_socket.open",
666 RawSocketError::NoSocket { .. } => "raw_socket.no_socket",
667 RawSocketError::HopLimit { .. } => "raw_socket.hop_limit",
668 RawSocketError::NotHeld { .. } => "raw_socket.not_held",
669 RawSocketError::Pin { .. } => "raw_socket.pin",
670 RawSocketError::Send { .. } => "raw_socket.send",
671 RawSocketError::Poisoned => "raw_socket.poisoned",
672 }
673 }
674}
675
676impl Coded for TransportError {
677 fn code(&self) -> &'static str {
678 match self {
679 TransportError::Capture(capture) => capture.code(),
680 TransportError::RawSocket(_) => "transport.raw_socket",
681 TransportError::NoEthernetInterface(_) => "transport.no_ethernet_interface",
682 }
683 }
684}
685
686impl Coded for SendError {
687 fn code(&self) -> &'static str {
688 match self {
689 SendError::Unroutable(_) => "send.unroutable",
690 SendError::Unresolved(_) => "send.unresolved",
691 SendError::HeldDown(_) => "send.held_down",
692 SendError::Refused(_) => "send.refused",
693 SendError::Unsupported(_) => "send.unsupported",
694 SendError::OutOfDescriptors => "send.out_of_descriptors",
695 }
696 }
697}
698
699impl Coded for ChannelError {
700 fn code(&self) -> &'static str {
701 match self {
702 ChannelError::Send { .. } => "channel.send",
703 ChannelError::Receive { .. } => "channel.receive",
704 }
705 }
706}
707
708#[cfg(feature = "packet-exchange")]
709impl Coded for ExchangeError {
710 fn code(&self) -> &'static str {
711 match self {
712 ExchangeError::Transport(transport) => transport.code(),
713 ExchangeError::Build(packet) => packet.code(),
714 ExchangeError::Send(send) => send.code(),
715 ExchangeError::NoSource(_) => "exchange.no_source",
716 }
717 }
718}
719
720impl Coded for StrategyError {
721 fn code(&self) -> &'static str {
722 match self {
723 StrategyError::Transport(transport) => transport.code(),
724 StrategyError::Channel(channel) => channel.code(),
725 StrategyError::Capture(capture) => capture.code(),
726 StrategyError::Interface { .. } => "strategy.interface",
727 StrategyError::MismatchedTransport { .. } => "strategy.mismatched_transport",
728 StrategyError::Probe(_) => "strategy.probe",
729 StrategyError::Panicked { .. } => "strategy.panicked",
730 }
731 }
732}
733
734impl Coded for ResolverError {
735 fn code(&self) -> &'static str {
736 match self {
737 ResolverError::NoServer => "rdns.no_server",
738 ResolverError::Transport(transport) => transport.code(),
739 }
740 }
741}
742
743#[cfg(test)]
753mod tests {
754 use super::*;
755
756 fn sample() -> Vec<&'static str> {
758 vec![
759 ScanError::WrongPhase.code(),
760 EvasionError::HopLimitZero.code(),
761 EvasionError::FragmentTooSmall {
762 mtu: 8,
763 minimum: 28,
764 }
765 .code(),
766 ExportError::Render {
767 format: "html",
768 message: String::new(),
769 }
770 .code(),
771 IpParseError::EmptySet.code(),
772 IpParseError::InvalidPrefix(33).code(),
773 TargetParseError::Empty.code(),
774 TargetParseError::UnknownHost("nowhere".into()).code(),
775 PortSetParseError::InvalidRange { start: 9, end: 1 }.code(),
776 PortSetParseError::MalformedSpec("x".into()).code(),
777 DetectionError::Parse("bad toml".into()).code(),
778 ]
779 }
780
781 #[test]
786 fn every_code_reads_area_then_what() {
787 for code in sample() {
788 let (area, what) = code
789 .split_once('.')
790 .unwrap_or_else(|| panic!("{code} names no area"));
791
792 assert!(!area.is_empty(), "{code} has an empty area");
793 assert!(!what.is_empty(), "{code} says nothing about what happened");
794 assert!(
795 code.chars()
796 .all(|c| c.is_ascii_lowercase() || c == '.' || c == '_'),
797 "{code} is not a lower-case dotted name"
798 );
799 }
800 }
801
802 #[test]
806 fn a_wrapping_error_reports_the_reason_rather_than_itself() {
807 assert_eq!(
808 ScanError::Evasion(EvasionError::HopLimitZero).code(),
809 "evasion.hop_limit_zero"
810 );
811
812 assert_eq!(
813 TargetParseError::Address {
814 expression: "10.0.0.".into(),
815 source: IpParseError::Malformed("10.0.0.".into()),
816 }
817 .code(),
818 "address.malformed"
819 );
820
821 assert_eq!(
822 TargetParseError::Ports {
823 expression: "198.51.100.1:x".into(),
824 source: PortSetParseError::MalformedSpec("x".into()),
825 }
826 .code(),
827 "ports.malformed_spec"
828 );
829 }
830
831 #[test]
835 fn a_panic_and_a_failure_are_not_the_same_code() {
836 let panicked = ScanError::TaskFailed {
837 panicked: true,
838 detail: "index out of bounds".into(),
839 };
840 let failed = ScanError::TaskFailed {
841 panicked: false,
842 detail: "cancelled".into(),
843 };
844
845 assert_eq!(panicked.code(), "scan.task_panicked");
846 assert_eq!(failed.code(), "scan.task_failed");
847 }
848
849 #[test]
854 fn the_codes_are_what_they_were() {
855 assert_eq!(ScanError::WrongPhase.code(), "scan.wrong_phase");
856 assert_eq!(
857 ScanError::TooFewDescriptors {
858 limit: 16,
859 needed: 17
860 }
861 .code(),
862 "scan.too_few_descriptors"
863 );
864 assert_eq!(
865 EvasionError::SourcePortZero.code(),
866 "evasion.source_port_zero"
867 );
868 assert_eq!(
869 EvasionError::PaddingTooLarge {
870 padding: 9000,
871 limit: 1500
872 }
873 .code(),
874 "evasion.padding_too_large"
875 );
876 assert_eq!(ExportError::Io(broken_pipe()).code(), "export.io");
877 assert_eq!(IpParseError::EmptySet.code(), "address.empty_set");
878 assert_eq!(
879 IpParseError::UnknownInterface("en9".into()).code(),
880 "address.unknown_interface"
881 );
882 assert_eq!(TargetParseError::Empty.code(), "target.empty");
883 assert_eq!(
884 TargetParseError::UnbalancedBracket("[::1".into()).code(),
885 "target.unbalanced_bracket"
886 );
887 assert_eq!(
888 PortSetParseError::InvalidRange { start: 9, end: 1 }.code(),
889 "ports.invalid_range"
890 );
891 assert_eq!(DetectionError::Tier("4".into()).code(), "detection.tier");
892 }
893
894 #[cfg(feature = "journal-format")]
897 #[test]
898 fn the_journal_codes_are_what_they_were() {
899 assert_eq!(JournalError::NotAJournal.code(), "journal.not_a_journal");
900 assert_eq!(
901 JournalError::VersionTooNew {
902 found: 9,
903 understood: 1
904 }
905 .code(),
906 "journal.version_too_new"
907 );
908 assert_eq!(
909 OpenError::Journal(JournalError::NotAJournal).code(),
910 "journal.not_a_journal",
911 "an open that failed on the format reports the format's reason"
912 );
913 }
914
915 #[test]
921 fn every_code_is_in_the_codebook_once() {
922 const WRITTEN: &[&str] = &[
923 "address.empty_set",
924 "address.invalid_prefix",
925 "address.invalid_range",
926 "address.keyword_unresolved",
927 "address.malformed",
928 "address.unknown_interface",
929 "address.zone_on_unscoped_target",
930 "advisories.malformed",
931 "advisories.not_advisories",
932 "advisories.too_large",
933 "advisories.unsupported_format",
934 "bundle.altered",
935 "bundle.duplicate",
936 "bundle.manifest",
937 "bundle.missing",
938 "bundle.too_many",
939 "bundle.unnamed",
940 "capability.byte_budget_exhausted",
941 "capability.connection_budget_exhausted",
942 "capability.connection_refused",
943 "capability.denied",
944 "capability.out_of_descriptors",
945 "capability.reset",
946 "capability.timed_out",
947 "capability.withheld",
948 "capture.denied",
949 "capture.filter",
950 "capture.library",
951 "capture.no_interface",
952 "capture.no_reader",
953 "capture.open",
954 "capture.out_of_descriptors",
955 "capture.unsupported_link_type",
956 "catalogue.io",
957 "catalogue.malformed",
958 "catalogue.reserved_id",
959 "catalogue.too_large",
960 "catalogue.unreadable_version",
961 "channel.receive",
962 "channel.send",
963 "compute.compile",
964 "compute.unsupported_body",
965 "config.unknown_detection_envelope",
966 "config.unknown_os_detection",
967 "config.unknown_scan_effort",
968 "config.unknown_scan_pace",
969 "config.unknown_sctp_technique",
970 "config.unknown_send_mode",
971 "config.unknown_service_detection",
972 "config.unknown_tcp_technique",
973 "config.unknown_tls_version",
974 "definition.generic_probe_not_tcp",
975 "definition.pattern",
976 "definition.probe_protocol",
977 "definition.udp_probe_size",
978 "definition.version_group",
979 "detection.body",
980 "detection.compute",
981 "detection.flow",
982 "detection.host",
983 "detection.parse",
984 "detection.pattern",
985 "detection.tier",
986 "detection.unused_body",
987 "evasion.fragment_too_small",
988 "evasion.hop_limit_zero",
989 "evasion.padding_too_large",
990 "evasion.source_port_zero",
991 "exchange.no_source",
992 "export.io",
993 "export.render",
994 "fetch.cancelled",
995 "fetch.certificate",
996 "fetch.connect",
997 "fetch.conversion",
998 "fetch.digest_mismatch",
999 "fetch.insecure",
1000 "fetch.interrupted",
1001 "fetch.invalid_id",
1002 "fetch.invalid_url",
1003 "fetch.network",
1004 "fetch.no_signature",
1005 "fetch.no_sources",
1006 "fetch.not_stored",
1007 "fetch.redirects",
1008 "fetch.setup",
1009 "fetch.status",
1010 "fetch.storage",
1011 "fetch.timed_out",
1012 "fetch.tls",
1013 "fetch.too_large",
1014 "fetch.unparsable_url",
1015 "finding.empty_group",
1016 "finding.empty_id",
1017 "finding.empty_title",
1018 "finding.malformed_version",
1019 "finding.no_exploited_cve",
1020 "flow.empty",
1021 "flow.expected",
1022 "flow.int_overflow",
1023 "flow.too_deep",
1024 "flow.trailing",
1025 "flow.unexpected_char",
1026 "flow.unterminated_string",
1027 "import.document_too_large",
1028 "import.io",
1029 "import.line_too_long",
1030 "import.malformed",
1031 "import.too_many_addresses",
1032 "import.too_many_hosts",
1033 "import.too_many_tokens",
1034 "journal.io",
1035 "journal.lock_io",
1036 "journal.locked",
1037 "journal.malformed",
1038 "journal.no_root",
1039 "journal.not_a_journal",
1040 "journal.not_an_id",
1041 "journal.option_changed",
1042 "journal.plan_changed",
1043 "journal.version_too_new",
1044 "journal.wrong_phase",
1045 "kev.io",
1046 "kev.malformed",
1047 "kev.too_large",
1048 "link.empty",
1049 "link.no_lan",
1050 "link.no_links",
1051 "link.unknown",
1052 "link.unreadable",
1053 "mac.malformed",
1054 "nvd.io",
1055 "nvd.malformed",
1056 "nvd.too_large",
1057 "nvd.too_many_entries",
1058 "packet.family_mismatch",
1059 "packet.header_has_options",
1060 "packet.mtu_too_small",
1061 "packet.options_misaligned",
1062 "packet.options_too_long",
1063 "packet.too_long",
1064 "packet.truncated",
1065 "packet.unexpected_message",
1066 "packet.unreadable",
1067 "packet.unsupported_ether_type",
1068 "packet.unwritable_name",
1069 "packet.wrong_family",
1070 "ports.empty",
1071 "ports.invalid_port",
1072 "ports.invalid_range",
1073 "ports.malformed_spec",
1074 "ports.service_name",
1075 "ports.spaced_range",
1076 "range.backwards",
1077 "range.invalid_prefix",
1078 "range.malformed",
1079 "range.malformed_address",
1080 "range.malformed_prefix",
1081 "raw_socket.hop_limit",
1082 "raw_socket.no_socket",
1083 "raw_socket.not_held",
1084 "raw_socket.open",
1085 "raw_socket.pin",
1086 "raw_socket.poisoned",
1087 "raw_socket.send",
1088 "rdns.no_server",
1089 "replay.diverged",
1090 "replay.grant_failed",
1091 "replay.run",
1092 "replay.unknown_detection",
1093 "replay.unknown_transport",
1094 "request.bad_ports",
1095 "request.no_targets",
1096 "rule.example_without_series",
1097 "rule.example_without_window",
1098 "rule.no_predicates",
1099 "rule.predicate",
1100 "rule.unidentified",
1101 "rule.version_without_product",
1102 "rule.weight",
1103 "scan.task_failed",
1104 "scan.task_panicked",
1105 "scan.too_few_descriptors",
1106 "scan.wrong_phase",
1107 "scoped_address.empty_zone",
1108 "scoped_address.not_an_address",
1109 "scoped_address.zone_on_unscoped",
1110 "send.held_down",
1111 "send.out_of_descriptors",
1112 "send.refused",
1113 "send.unresolved",
1114 "send.unroutable",
1115 "send.unsupported",
1116 "settings.io",
1117 "settings.malformed",
1118 "settings.no_path",
1119 "settings.too_large",
1120 "settings.unknown_profile",
1121 "signature.altered",
1122 "signature.invalid",
1123 "signature.io",
1124 "signature.malformed",
1125 "signature.unknown_algorithm",
1126 "signature.unreadable_key",
1127 "signature.untrusted_key",
1128 "strategy.interface",
1129 "strategy.mismatched_transport",
1130 "strategy.panicked",
1131 "strategy.probe",
1132 "target.blank",
1133 "target.capacity_overflow",
1134 "target.empty",
1135 "target.empty_ports",
1136 "target.mistyped_address",
1137 "target.no_host_lookup",
1138 "target.resolved_to_nothing",
1139 "target.trailing_text",
1140 "target.unbalanced_bracket",
1141 "target.unbracketed_address",
1142 "target.unknown_host",
1143 "transport.no_ethernet_interface",
1144 "transport.raw_socket",
1145 ];
1146
1147 let source = include_str!("error.rs");
1148 let codes_end = source
1149 .find("#[cfg(test)]\nmod tests")
1150 .expect("the tests module");
1151 let mut handed_out: Vec<&str> = source[..codes_end]
1152 .lines()
1153 .filter(|line| !line.trim_start().starts_with("//"))
1154 .flat_map(|line| line.split('"').skip(1).step_by(2))
1155 .filter(|quoted| {
1156 quoted.split_once('.').is_some_and(|(area, what)| {
1157 !area.is_empty()
1158 && !what.is_empty()
1159 && quoted
1160 .chars()
1161 .all(|c| c.is_ascii_lowercase() || c == '.' || c == '_')
1162 })
1163 })
1164 .collect();
1165 handed_out.sort_unstable();
1166
1167 let mut unique = handed_out.clone();
1168 unique.dedup();
1169 assert_eq!(handed_out, unique, "a code handed out by two arms");
1170 assert_eq!(handed_out, WRITTEN, "the codes and the codebook differ");
1171 }
1172
1173 fn broken_pipe() -> std::io::Error {
1174 std::io::Error::new(std::io::ErrorKind::BrokenPipe, "gone")
1175 }
1176}