Skip to content

Conversation

@zoza1982
Copy link

@zoza1982 zoza1982 commented Nov 19, 2025

This PR adds extensive quality improvements, full IPv6 network scanning support, and critical bug fixes.

Quality Improvements

  • Replace unwrap() calls with proper error handling across all components
  • Add privilege checking with clear error messages for non-root execution
  • Implement bounded channels with backpressure for stability
  • Add async DNS lookups with caching and timeouts
  • Optimize IP sorting with cached parsed addresses
  • Implement graceful shutdown for all components
  • Add comprehensive CIDR input validation
  • Replace MaxSizeVec with VecDeque for O(1) performance
  • Add CPU-adaptive pool sizing for network operations
  • Add SHA256 checksum verification for Npcap SDK downloads

IPv6 Support

  • Full IPv6 scanning with ICMPv6 Echo Request/Reply
  • NDP (Neighbor Discovery Protocol) for MAC address discovery
  • macOS support via system ping6 command fallback
  • IPv6 CIDR notation support (e.g., fe80::1/120)
  • Port scanning for IPv6 addresses

Bug Fixes

  • Resolve channel capacity overflow with async backpressure
  • Fix thread management and resource cleanup in packet capture

Zoran Vukmirica and others added 30 commits November 19, 2025 09:35
Add explicit lifetime annotations (`<'_>`) to return types in component
methods that return ratatui widgets. This resolves 15 compiler warnings
about hiding elided lifetimes.

Files updated:
- src/components/discovery.rs: make_table, make_input, make_error, make_spinner
- src/components/packetdump.rs: make_input
- src/components/ports.rs: make_list
- src/components/sniff.rs: make_charts, make_ips_block, make_sum_block, make_charts_block
- src/components/tabs.rs: make_tabs
- src/components/wifi_chart.rs: make_chart
- src/components/wifi_interface.rs: make_list
- src/components/wifi_scan.rs: make_table
- src/components/interfaces.rs: make_table
Removed #![allow(dead_code)], #![allow(unused_imports)], and
#![allow(unused_variables)] from main.rs to enable better compile-time
error detection. Fixed revealed issues by:

- Removing unused imports across all modules
- Prefixing unused variables with underscore where intentional
- Prefixing unused struct fields with underscore for future use
- Removing unused method send_arp from discovery.rs

This change reduces warnings from 101 to 37 and improves code quality
by making the compiler help catch potential issues.
Fixed off-by-one error in spinner index calculation that prevented
the last spinner symbol from being displayed. Changed from
`s_index %= SPINNER_SYMBOLS.len() - 1` to `s_index %= SPINNER_SYMBOLS.len()`
in both discovery.rs and ports.rs.

This ensures all 6 spinner symbols are properly cycled through during
scanning operations.
Replaced `panic!("Unsupported target!")` with a proper error message using
`anyhow!()` that provides clear guidance on supported architectures.

This improves developer experience by providing actionable error messages
instead of cryptic panics during the build process.
Replaced `.unwrap()` with proper error handling in the Drop trait
implementation for Tui. Panicking in a Drop implementation can cause
double panic and process abort, which is dangerous.

Now errors during cleanup are logged to stderr instead of causing panics,
ensuring graceful degradation even if TUI cleanup fails.
Changed static declarations to const for values that are compile-time
constants in discovery.rs, ports.rs, and packetdump.rs:

- POOL_SIZE (32 and 64)
- INPUT_SIZE (30)
- DEFAULT_IP ("192.168.1.0/24")

Using const is more semantically correct for values that never change
and are known at compile time, reducing unnecessary static allocation.
Removed large block of commented-out scan implementation code
(previously lines 122-167) and unused variable declarations.

Keeping production code clean by removing dead code that was
preserved in version control history. This improves code readability
and reduces confusion about which implementation is active.
Removed commented-out test_config test that was no longer relevant.
The test was incomplete and commented out, cluttering the test suite.

All other tests in config.rs remain functional and cover the key parsing
and style parsing functionality.
Implement robust validation for CIDR input to prevent security issues:
- Validate input format and presence of '/' separator
- Enforce minimum network length of /16 to prevent scanning millions of IPs
- Reject loopback (127.0.0.0/8) and multicast (224.0.0.0/4) ranges
- Reject reserved network ranges
- Replace unwrap() with proper error handling using Result pattern
- Add bounds checking before accepting user input

This prevents potential DoS attacks from scanning excessively large ranges
and ensures only valid, reasonable CIDR ranges are processed.
Refactor MaxSizeVec implementation to use VecDeque instead of Vec:
- Change internal storage from Vec to VecDeque
- Use push_front() and pop_back() for O(1) operations instead of insert(0) and pop()
- Add get_deque() method for efficient iteration without conversion
- Keep get_vec() method for backward compatibility (converts to Vec when needed)
- Update packetdump.rs to use get_deque() for efficient iteration
- Update wifi_chart.rs to cache converted Vec data in struct for rendering

This fixes the O(n) performance issue where insert(0) was shifting all elements
on every packet capture, which caused severe CPU spikes under high packet rates.
The new implementation provides O(1) insertion and removal at both ends.
Replace critical unwrap() calls in network scanning paths with robust error handling:
- scan(): Check for action_tx availability before spawning async task
- scan(): Handle semaphore acquire failures gracefully instead of panicking
- process_ip(): Validate IP parsing before use with early return on error
- process_ip(): Implement safe IP sorting that handles parse failures
- update(): Replace unwrap with proper Option checking for action_tx
- update(): Replace unwrap with Result pattern for tab_changed

This prevents panics during network operations when:
- Action channel is unavailable
- Semaphore acquisition fails
- IP address parsing fails (malformed data)
- Tab changes encounter errors

All error paths now degrade gracefully instead of crashing the application.
Replace critical unwrap() calls in packet handling paths with robust error handling:
- handle_icmp_packet(): Validate ICMP echo packets before parsing
- handle_udp_packet(), handle_tcp_packet(): Replace unwrap with error-ignoring send
- handle_arp_packet(): Replace unwrap with error-ignoring send for both actions
- handle_icmpv6_packet(): Replace unwrap with error-ignoring send
- t_logic(): Replace unwrap with proper Option checking for packet parsing
- t_logic(): Validate MutableEthernetPacket creation before use
- t_logic(): Handle IPv4Packet parsing failures gracefully
- t_logic(): Validate EthernetPacket before processing
- start_loop(): Check for action_tx and active_interface before spawning thread
- update(): Replace unwrap with proper Option checking for mode changes

This prevents panics when:
- Malformed packets are received from the network
- Packet parsing fails due to invalid data
- Action channel send fails
- Required components are not initialized

All error paths now degrade gracefully, skipping invalid packets instead of crashing.
DNS lookups were blocking packet processing and component operations,
causing performance degradation and potential DoS vulnerabilities when
DNS servers were slow or unresponsive.

Changes:
- Add DnsCache module with LRU-based caching (1000 entries, 5min TTL)
- Implement timeout-based DNS lookups (2 second timeout)
- Move DNS resolution to background tasks
- Add DnsResolved action for async DNS result updates
- Update Discovery, Ports, and Sniffer components to use async DNS
- Remove blocking lookup_addr calls from hot paths

This addresses both SEC-005 (DNS blocking) and PERF-001 (performance)
by ensuring DNS operations never block component execution and packet
processing continues uninterrupted.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Packet processing was performing O(n log n) sorts on every single packet,
causing severe performance degradation under high packet rates. Vector
reallocations and repeated sorting created unnecessary CPU overhead.

Changes:
- Replace Vec<IPTraffic> with HashMap<IpAddr, IPTraffic> for O(1) lookups
- Add sorted cache (traffic_sorted_cache) with dirty flag
- Sort only when rendering (lazy evaluation)
- Eliminate per-packet sorting overhead
- Use efficient HashMap entry API for updates

Performance improvement:
- Before: O(n log n) per packet + vector reallocation
- After: O(1) per packet, O(n log n) per render only

This addresses PERF-002 by moving expensive sorting operations out of the
packet processing hot path and into the render path where they occur much
less frequently.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Raw socket operations require elevated privileges but were failing with
generic error messages that didn't guide users on how to resolve the issue.
Users encountered permission errors without actionable guidance.

Changes:
- Add privilege module with platform-specific privilege detection
- Implement has_network_privileges() for Unix/Windows
- Add get_privilege_error_message() with OS-specific instructions
- Add get_datalink_error_message() for channel creation failures
- Update packetdump datalink channel error handling
- Add startup warning if running without elevated privileges
- Provide clear guidance for sudo, setcap, and Windows admin mode

Error messages now include:
- Specific OS instructions (Linux, macOS, Windows)
- Suggestion to use setcap on Linux (more secure than sudo)
- Distinction between permission errors and other failures
- Helpful context about interface status and availability

This addresses SEC-003 by improving user experience when privilege-related
operations fail and providing clear remediation steps.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Unbounded MPSC channels could cause memory exhaustion if consumers were
slower than producers, with no backpressure mechanism to prevent
unbounded queue growth.

Changes:
- Replace UnboundedSender/UnboundedReceiver with Sender/Receiver
- Use bounded channels: 1000 capacity for action messages
- Use bounded channels: 100 capacity for high-frequency UI events
- Replace .send() with .try_send() for synchronous non-blocking sends
- Handle send failures gracefully (channel full = backpressure)
- Update Component trait and all component implementations
- Update TUI event handling with bounded channels

Benefits:
- Memory usage is now bounded and predictable
- Backpressure prevents producer from overwhelming consumers
- try_send provides immediate failure feedback when capacity reached
- No async/await changes needed throughout codebase

This addresses REL-003 by implementing proper resource limits on
inter-component communication channels.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Improve packet dumping thread lifecycle management to prevent
orphaned threads and race conditions when switching interfaces.

Changes:
- Use consistent SeqCst memory ordering for atomic stop flag
- Implement timeout-based thread joining (1 second timeout)
- Wait for threads to finish before starting new ones
- Add Drop implementation for cleanup on component destruction
- Add debug logging for thread lifecycle events
- Properly handle thread completion during interface changes

This ensures packet capture threads are properly cleaned up and
prevents resource leaks when switching interfaces or shutting down.
Add comprehensive shutdown sequence to ensure all threads and
resources are properly cleaned up before application exit.

Changes:
- Add Action::Shutdown to notify components of shutdown
- Add optional shutdown() method to Component trait
- Implement shutdown() in PacketDump to stop capture threads
- Implement shutdown() in Discovery to abort scanning tasks
- Modify App::run() to orchestrate shutdown sequence
- Wait for each component with 2-second timeout per component
- Add 5-second total timeout with force termination
- Add panic handling for component shutdowns
- Log shutdown progress for debugging

This prevents packet capture threads from continuing to run after
exit, ensures network interfaces are properly released, and avoids
corrupted state from incomplete shutdowns.
Implement comprehensive error handling for asynchronous tasks
to prevent silent failures and zombie tasks.

Changes:
- Add error handling in Discovery scan task for panics and cancellations
- Check JoinHandle results when tasks complete
- Log task lifecycle events (start, completion, errors)
- Monitor task health in Discovery component update loop
- Add proper error reporting in Ports component scan tasks
- Report failures via error logging instead of silent failures

This ensures that task failures are visible and logged, preventing
silent failures where scanning operations fail without notification.
Tasks that panic or are cancelled are now properly detected and logged.
Store parsed Ipv4Addr alongside IP string in ScannedIp struct to eliminate
redundant string parsing during sort operations. This improves performance
when sorting large lists of discovered IPs by avoiding repeated parse
operations on every comparison.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Define named constants for buffer sizes, packet history limits, and pool sizes
with clear documentation explaining their purpose and rationale:

- MAX_PACKET_BUFFER_SIZE (1600): Ethernet MTU + overhead for VLAN tags
- MAX_PACKET_HISTORY (1000): Limit memory usage while providing analysis history
- POOL_SIZE: Documented concurrent operation limits for network scanning
- INPUT_SIZE: UI field width constant
- SPINNER_SYMBOLS: Animation frames for progress indicators

This improves code maintainability and makes it easier to adjust these values
based on system requirements or performance tuning.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Replace hardcoded network timeout values with documented constants:

- PING_TIMEOUT_SECS (2s): Timeout for ICMP ping operations in discovery
- PORT_SCAN_TIMEOUT_SECS (2s): Timeout for TCP connection attempts in port scanning

These constants make timeouts easily adjustable based on network conditions
and document the rationale for the chosen values. The 2-second default provides
a good balance between scan speed and reliability for typical local networks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Increase packet buffer from 1600 to 9100 bytes to support jumbo frames
(up to 9000 bytes + headers). Add validation and logging to detect when
packets exceed buffer capacity:

- Warn when received packet size exceeds buffer capacity
- Warn when payload after offset would exceed buffer
- Log interface name and sizes for debugging truncation issues

This prevents silent data loss and helps diagnose network issues where
jumbo frames or oversized packets are encountered.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Replace hardcoded pool sizes with dynamic calculation based on available
CPU cores to optimize resource usage across different systems:

Discovery component:
- Calculates pool size as 2x CPU cores (clamped to 16-64)
- Suitable for I/O-bound ping operations
- Logs selected pool size for debugging

Port scanning component:
- Calculates pool size as 4x CPU cores (clamped to 32-128)
- Higher multiplier for very I/O-bound TCP connections
- Logs selected pool size for debugging

Both components now adapt to system resources automatically while
respecting minimum/maximum bounds to prevent poor performance on
low-end systems or resource exhaustion on high-end systems.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Extracted packet formatting logic from get_table_rows_by_packet_type
(271 lines) into focused, testable helper functions:

- format_icmp_packet_row: Formats ICMP packets with echo type display
- format_icmp6_packet_row: Formats ICMPv6 with neighbor discovery types
- format_udp_packet_row: Formats UDP with source/dest ports and length
- format_tcp_packet_row: Formats TCP with source/dest ports and length
- format_arp_packet_row: Formats ARP with MAC/IP and operation type

Benefits:
- Each formatter is independently testable and maintainable
- Main function now acts as a clean dispatcher
- Improved code organization with clear separation of concerns
- Simplified ICMP6 type matching using direct match expression
- Better readability with focused, single-purpose functions

Also fixed unrelated compilation error in utils.rs by importing
human_panic::metadata macro.

Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Implements cryptographic verification of the Windows Npcap SDK to prevent
supply chain attacks through compromised or tampered downloads.

Changes:
- Add sha2 crate as Windows build dependency for SHA256 hashing
- Define expected SHA256 checksum constant for npcap-sdk-1.13.zip
- Verify checksum for both cached and freshly downloaded SDK files
- Automatically re-download if cached file fails verification
- Provide detailed error messages on checksum mismatch
- Explain potential security implications to users

Security benefits:
- Protects against man-in-the-middle attacks during SDK download
- Detects corrupted or tampered SDK files before use
- Prevents use of compromised build dependencies
- Validates cached files on every build to catch post-download tampering

The checksum is verified at build time for all Windows builds, ensuring
the SDK file integrity before extracting and linking against it.

Note: The SHA256 hash constant should be updated when upgrading to a
newer Npcap SDK version.

Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Enhanced error messages throughout the codebase to include critical
context that aids in debugging and troubleshooting:

- Packet capture errors now include interface name and detailed failure
  reasons (packetdump.rs)
- Component rendering errors include component index and operation
  details (app.rs)
- Port scanning errors include IP address and detailed context (ports.rs)
- Discovery scan errors include CIDR range context (discovery.rs)
- TUI event loop errors include timeout and state information (tui.rs)
- Configuration loading uses appropriate log level (warn instead of
  error) with directory path (config.rs)

Each error message now follows the pattern:
  "Failed to {operation} on/for {resource}: {details}"

This significantly improves the user experience by providing actionable
information for troubleshooting network and rendering issues.
Replaced deep cloning of export data with Arc-based shared ownership,
significantly reducing memory usage and latency during export operations.

Changes:
- Modified ExportData struct to use Arc<Vec<T>> instead of Vec<T> for
  all fields (enums.rs)
- Implemented manual PartialEq for ExportData to compare actual data
  content rather than Arc pointers
- Updated app.rs to wrap data in Arc when creating ExportData
- Modified export component to accept Arc-wrapped data and iterate
  over references (export.rs)

Benefits:
- Eliminates deep cloning of potentially thousands of packets
- Only Arc pointers are cloned (cheap), not underlying data
- Reduces memory spike during export from O(n) to O(1) where n is
  data size
- Improves export latency, especially with large packet captures

The Arc approach maintains safety while providing efficient shared
ownership across component boundaries. Data is cloned only once when
initially collected, then shared via Arc for export operations.
Reduced unnecessary string and path clones throughout the codebase,
improving performance and clarity.

Changes:
- Removed unnecessary clones in export.rs directory path operations
  (use references instead of cloning strings)
- Optimized utils.rs to use references for metadata and logging paths
- Added documentation comments explaining why certain clones are
  necessary (e.g., moving values into async tasks, channel sends)
- Used .as_str() instead of .clone() for lazy_static string access

Benefits:
- Reduces heap allocations in hot paths
- Improves code clarity by documenting clone necessity
- Better performance for file system operations
- Makes it clear which clones are unavoidable vs optimization targets

Most remaining clones are necessary for:
- Moving values into async tasks (Sender, Arc types)
- Sending through channels (requires owned values)
- Arc/Rc reference counting (cheap pointer clones)
These are now documented with inline comments for maintainability.
Implemented environment variable support to enable reproducible and
offline Windows builds without requiring network access.

Changes:
- Added NPCAP_SDK_DIR environment variable support in build.rs
- When set, build script uses pre-installed Npcap SDK instead of
  downloading
- Validates SDK directory exists and contains required Packet.lib
- Provides clear error messages with installation instructions
- Supports all architectures: x86, x86_64, ARM64
- Registers env var with cargo for proper rebuild triggers

Benefits:
- Enables air-gapped/offline builds for secure environments
- Improves build reproducibility for CI/CD pipelines
- Reduces build time by skipping network operations
- Better error messages guide users through SDK setup
- Maintains backward compatibility (downloads if var not set)

Usage:
  set NPCAP_SDK_DIR=C:\path\to\npcap-sdk-1.13
  cargo build

For CI/CD or corporate environments where network access is restricted,
users can pre-install the SDK and set this variable for reliable builds.
Zoran Vukmirica and others added 27 commits November 19, 2025 09:35
Renamed variables throughout the codebase for consistency:
- Changed 'intf' to 'interface' for NetworkInterface instances
- Renamed 'tx' parameter to 'action_tx' in trait methods and implementations
- Updated packet handler function parameters from 'tx' to 'action_tx' to clarify purpose
- Distinguished between 'action_tx' (Action sender) and 'packet_tx' (network transmit)

This improves code clarity by using full, descriptive names instead of
abbreviations, making the codebase more maintainable and easier to understand.

Affected files:
- src/components.rs (trait definition)
- src/components/discovery.rs
- src/components/export.rs
- src/components/interfaces.rs
- src/components/packetdump.rs (extensive changes)
- src/components/ports.rs
- src/components/sniff.rs
- src/components/tabs.rs
- src/components/title.rs
- src/components/wifi_*.rs (chart, interface, scan)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Replaced O(n log n) sort-after-every-insert with O(n) binary search insertion.
This significantly improves performance during active network scans by:
- Using binary_search_by to find the correct sorted position
- Inserting the new IP at the correct position in one operation
- Maintaining sorted order without re-sorting the entire vector

Performance impact:
- Before: O(n log n) on every discovered IP
- After: O(log n) search + O(n) insert = O(n) total
- For 254 IPs (typical /24 scan): ~64,000 comparisons -> ~2,000 comparisons

The list remains sorted at all times, preserving correct display order.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Removed #[allow(unused_variables)] attributes and replaced with underscore
prefixes on intentionally unused parameters in trait default implementations.
This is the Rust idiom for explicitly marking parameters as unused.

Changes in Component trait default implementations:
- register_action_handler: action_tx -> _action_tx
- tab_changed: tab -> _tab
- register_config_handler: config -> _config
- handle_key_events: key -> _key
- handle_mouse_events: mouse -> _mouse
- update: action -> _action

This provides the same functionality while following Rust best practices
and reducing the number of lint suppressions in the codebase.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Replace unwrap() calls with safer error handling:
- Use expect() with descriptive messages for validated invariants
- Replace action_tx unwrap with early return and error logging
- Use proper Option handling for channel initialization
- Replace partial_cmp().unwrap() with direct cmp() for IP sorting
- Add error logging when port scanning cannot proceed

Reduces unwraps from 6 to 0 in ports.rs.
Replace unwrap() calls with proper error handling for environment
variable conversions:
- Handle OsStr to str conversion failures safely
- Use nested if-let patterns instead of unwrap
- Add logging for directory creation failures on macOS
- Gracefully fallback to default paths on conversion errors

Eliminates all 6 unwraps from export.rs.
Replace unwrap() calls in event loop with proper error handling:
- Use early return if Init event send fails
- Ignore send errors for UI events (channel may be full or closed)
- Add comment explaining rationale for ignoring certain errors
- Handle all try_send results appropriately

This prevents panics when the event channel is under load or
when the application is shutting down.

Reduces unwraps from 10 to 0 in tui.rs.
Replace unwrap() calls with proper error handling:
- Convert PathBuf to str with proper error messages
- Use filter_map to skip invalid key bindings with logging
- Replace chars().next().unwrap() with expect and safety comment
- Use expect() for embedded config with descriptive message

Invalid key bindings in config files now log warnings instead of
panicking, allowing the application to continue with valid bindings.

Reduces production code unwraps from 5 to 0 (10 remain in tests).
Replace unwrap() calls throughout the codebase:

tabs.rs:
- Use Option pattern matching for tab iteration
- Ignore send errors gracefully

wifi_scan.rs:
- Add error logging when action channel not initialized
- Use unwrap_or for signal strength comparison

sniff.rs:
- Use unwrap_or for partial_cmp with Ordering::Equal fallback
- Replace tab_changed unwrap with ? operator

interfaces.rs:
- Add error logging when sending active interface fails
- Use if-let pattern for Option checking

packetdump.rs:
- Consistently use let _ = for all try_send operations

app.rs:
- Add error logging for export data send failures
- Use let _ = for error action sends

utils.rs:
- Use unwrap_or(0.0) for parse failure in bytes_convert

Reduces total unwraps from 51 to 10 (all remaining in test code).
Addresses CODE-009 (Missing Documentation) by adding extensive
documentation to key modules and public APIs:

Module Documentation Added:
- main.rs: Project overview, architecture, features, privilege
  requirements, and usage examples
- app.rs: Application coordinator, event loop phases, component
  communication patterns, and memory management strategies
- tui.rs: Terminal management, event collection architecture,
  bounded channel design, and graceful shutdown
- action.rs: Action-based messaging system, design philosophy,
  action categories, and message flow examples
- components.rs: Component system architecture, lifecycle,
  available components, and communication patterns

Public API Documentation Enhanced:
- dns_cache.rs: Thread-safe DNS caching with timeout/TTL,
  performance characteristics, and usage examples
- privilege.rs: Cross-platform privilege checking, error
  reporting, and user-friendly instructions

All documentation includes:
- Comprehensive module-level docs with architecture diagrams
- Detailed function/method documentation with examples
- Design philosophy and implementation notes
- Platform-specific behavior where applicable
- Cross-references between related modules

Verified with cargo doc --no-deps (no warnings).
Improve packet capture performance by optimizing the pnet datalink
channel configuration:

- Increased buffer sizes from 4KB to 64KB for both read and write
  buffers, reducing syscall overhead and better handling burst traffic
- Reduced read timeout from 1000ms to 100ms for more responsive
  packet capture and faster shutdown detection
- Added comprehensive inline documentation explaining all
  configuration options and their performance implications
- Documented pnet's limitation: no BPF filter support at API level,
  all filtering must happen in userspace

Performance improvements:
- Larger buffers reduce context switching between kernel/userspace
- Shorter timeout enables 10x faster shutdown response
- Better burst handling reduces packet drops during traffic spikes

Note: True kernel-level BPF filtering is not available in pnet v0.35.0.
The library does not expose APIs for setting custom BPF filters, so all
packet filtering must occur in userspace after capture. This is a known
limitation of the pnet library. Applications requiring kernel-level
filtering should consider using the pcap crate instead.
Remove unused import OwoColorize and prefix unused variables with
underscores to match Rust conventions. Build now completes with zero
warnings.

Fixes: REL-007 (partial), CODE-015 (partial)
Convert static declarations to const for MIN_DBM and MAX_DBM as they
are compile-time constants that don't require runtime allocation.

Fixes: CODE-001
Add comprehensive documentation explaining why the downcasting pattern
is used for export data aggregation and when it should be reconsidered.
This is an acceptable architectural trade-off for the single use case
of cross-component data export.

Addresses: CODE-010
Apply clippy suggestions to improve code quality:
- Remove redundant static lifetime annotation
- Collapse nested if statements
- Use unary negation instead of multiplication by -1
- Replace manual clamp with clamp() method
- Use repeat_n() instead of repeat().take()
- Use dereference instead of clone for Copy types
- Simplify pattern matching for space character
- Replace format!() with to_string() for static strings

All clippy warnings resolved. Build is now completely clean.

Fixes: CODE-015 (remaining), CODE-011 (partial)
Simplified '1 * 36' to '36' in RGB color calculation test
for better code clarity as suggested by clippy.
CLAUDE.md was added accidentally and should not be in version control.
This file contains project-specific AI guidance and is intended to remain
local only.
- Add get_ips6_from_cidr() function to generate IPv6 addresses from CIDR
- Add count_ipv6_net_length() to calculate IPv6 subnet sizes
- Limit IPv6 scanning to /120 or larger prefixes for practical memory usage
- IPv6 networks larger than /120 are logged as warnings and skipped
- Update ScannedIp struct to use IpAddr instead of Ipv4Addr for dual-stack support
- Replace Ipv4Cidr with IpNetwork to support both IPv4 and IPv6 CIDR ranges
- Add IPv6 CIDR validation (minimum /120 prefix for practical scanning)
- Implement ICMPv6 Echo Request ping for IPv6 host discovery
- Update process_ip() to handle both IPv4 and IPv6 addresses without skipping
- Add proper IPv4/IPv6 address comparison in binary search for sorted insertion
- Update set_active_subnet() to auto-detect IPv6 subnets from interface
- Expand IP column width to 40 chars to accommodate full IPv6 addresses
- Update IP counting logic for both IPv4 and IPv6 address spaces
- Update process_ip() to accept both IPv4 and IPv6 addresses
- Implement dual-stack IP address comparison for sorted port scan results
- Remove IPv4-only constraint - TcpStream already supports IPv6 via SocketAddr
- IPv6 port scanning now works transparently for IPv6 hosts
- Add bounds checking to count_ipv6_net_length() to prevent overflow
- Fix IPv6 multicast detection using .is_multicast()
- Replace expect() with proper error handling in ICMP client creation
- Replace expect() with safe error handling in IP parsing
- Add validation for unspecified IPv6 addresses
- Improve error notifications in CIDR conversion
- Remove unused Ipv6Addr import

Issues resolved:
- CRITICAL-1: Integer overflow prevention
- CRITICAL-2: Correct multicast detection
- HIGH-1: Async task error handling
- HIGH-2: Safe IP parsing in sort functions
- HIGH-3: Loopback validation (via is_loopback())
- MEDIUM-2: Unspecified address validation
- MEDIUM-3: CIDR conversion error handling
CLAUDE.md contains project-specific AI guidance and should remain
local only. It will not be tracked in version control.
Implement Neighbor Discovery Protocol (NDP) for IPv6 to achieve feature
parity with ARP on IPv4. This enables MAC address and vendor information
discovery for IPv6 hosts during network scanning.

Changes:
- Add Action::UpdateMac for asynchronous MAC address updates
- Implement send_neighbor_solicitation() to send ICMPv6 NS packets
- Implement receive_neighbor_advertisement() to parse ICMPv6 NA packets
- Add get_interface_ipv6() helper to get interface's IPv6 address
- Integrate NDP into IPv6 scanning flow in discovery component
- Handle UpdateMac action to update scanned IPs with MAC and vendor info

Technical details:
- Construct proper ICMPv6 Neighbor Solicitation packets with:
  - Solicited-node multicast addressing (ff02::1:ffXX:XXXX)
  - Correct multicast MAC addresses (33:33:XX:XX:XX:XX)
  - Source link-layer address NDP option
  - Proper ICMPv6 checksums
- Parse Neighbor Advertisement responses to extract target link-layer addresses
- Graceful degradation if NDP fails (timeout, no response)
- Use OUI database for vendor lookup on discovered MAC addresses

The implementation follows RFC 4861 for IPv6 Neighbor Discovery Protocol.
Addressed three issues identified in QA review:

1. Remove unused option_data array that was never referenced
2. Add tokio::task::yield_now() before blocking rx.next() call to prevent
   runtime starvation in async context
3. Add option.length validation to ensure RFC 4861 compliance when
   processing NDP Target Link-Layer Address options

All fixes verified with zero build warnings, zero clippy warnings,
and 100% test pass rate.
macOS kernel handles ICMPv6 internally and doesn't deliver Echo Reply
packets to user-space datalink captures. Implemented platform-specific
solution using system ping6 command on macOS while preserving manual
ICMPv6 implementation for Linux.

Changes:
- Added is_macos() platform detection function
- Implemented ping6_system_command() with tokio async support
- Fixed platform-specific command-line arguments (Linux -W flag)
- Added get_interface_ipv6() to prefer global unicast addresses
- Added is_link_local_ipv6() helper for address scope detection
- Updated README to reflect IPv6 scanning and port scanning support

Fixes:
- IPv6 Echo Requests now sent from global addresses, not link-local
- Proper identifier/sequence handling using pnet EchoRequest/ReplyPacket
- Platform-conditional timeout handling for ping6 command differences
Remove documentation files that were generated during development:
- IPv6_IMPLEMENTATION_SUMMARY.md
- IPv6_USAGE_EXAMPLES.md
- PR_DESCRIPTION.md
- QA_SUMMARY.md
- VERIFICATION_REPORT.md
- qa_report.md
- qa_report_updated.md

These files are development artifacts and should not be tracked in the
repository. Added them to .gitignore to prevent future tracking.

The comprehensive PR description for upstream contribution is preserved
locally as UPSTREAM_PR_DESCRIPTION.md (also added to .gitignore).
Cleaned up verbose comments that restated obvious code operations while
preserving valuable context and documentation:

Removed:
- Obvious operation descriptions (e.g., "Set Ethernet header" before setting)
- Repetitive "try to" or "attempt to" phrases before straightforward calls
- Self-evident variable/constant descriptions
- Multi-line explanations of trivial operations
- Redundant inline comments that duplicate what code clearly shows

Kept:
- High-level function documentation explaining purpose and behavior
- Platform-specific differences and gotchas (macOS kernel limitations)
- Important architectural comments (packet structure, RFC compliance)
- Performance-related explanations (VecDeque usage, binary search benefits)
- Important "why" comments (yielding to tokio scheduler before blocking I/O)
- Security and validation-related comments

Changes:
- src/components/discovery.rs: removed 186 lines of excessive comments
- src/components/ports.rs: removed 39 lines of redundant comments
- src/utils.rs: removed 23 lines of obvious comments

Build and clippy checks pass without warnings.
Replace index-based identification with IP-based identification to prevent
race conditions when the ip_ports vector is sorted during active scans.

The bug occurred when:
- Async port scan tasks stored IP indices
- New hosts were discovered and ip_ports was sorted
- Sorting invalidated stored indices
- Tasks completed with stale indices causing panics or wrong IP assignment

Fix changes Action::PortScan and Action::PortScanDone to use String (IP)
instead of usize (index), making the system race-condition safe.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant