Skip to main content

shadow_core/
transport.rs

1use async_trait::async_trait;
2use bytes::Bytes;
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6use crate::error::Result;
7use crate::packet::Packet;
8use crate::peer::{PeerId, PeerInfo};
9
10/// Cover protocols for traffic mimicry
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub enum CoverProtocol {
13    /// WebRTC video/audio conferencing
14    WebRTC,
15    /// HTTPS web browsing
16    HTTPS,
17    /// DNS queries
18    DNS,
19    /// IoT device communication (MQTT, CoAP)
20    IoT,
21    /// Gaming protocols (UDP-based)
22    Gaming,
23    /// Custom protocol
24    Custom,
25}
26
27impl fmt::Display for CoverProtocol {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            CoverProtocol::WebRTC => write!(f, "WebRTC"),
31            CoverProtocol::HTTPS => write!(f, "HTTPS"),
32            CoverProtocol::DNS => write!(f, "DNS"),
33            CoverProtocol::IoT => write!(f, "IoT"),
34            CoverProtocol::Gaming => write!(f, "Gaming"),
35            CoverProtocol::Custom => write!(f, "Custom"),
36        }
37    }
38}
39
40/// Transport layer abstraction for sending/receiving packets
41#[async_trait]
42pub trait Transport: Send + Sync {
43    /// Get the cover protocol being mimicked
44    fn protocol(&self) -> CoverProtocol;
45
46    /// Send a packet to a peer
47    async fn send(&mut self, packet: Packet, peer: &PeerInfo) -> Result<()>;
48
49    /// Receive a packet (blocks until one is available)
50    async fn recv(&mut self) -> Result<Packet>;
51
52    /// Get transport statistics
53    fn stats(&self) -> TransportStats;
54
55    /// Start background traffic generation (dummy packets, etc.)
56    async fn start_background_traffic(&mut self) -> Result<()>;
57
58    /// Stop background traffic generation
59    async fn stop_background_traffic(&mut self) -> Result<()>;
60
61    /// Adjust bandwidth usage (for adaptive quality)
62    async fn set_bandwidth_limit(&mut self, bytes_per_sec: u64) -> Result<()>;
63}
64
65/// Statistics about transport layer performance
66#[derive(Debug, Clone, Default, Serialize, Deserialize)]
67pub struct TransportStats {
68    /// Total packets sent
69    pub packets_sent: u64,
70    
71    /// Total packets received
72    pub packets_received: u64,
73    
74    /// Total bytes sent
75    pub bytes_sent: u64,
76    
77    /// Total bytes received
78    pub bytes_received: u64,
79    
80    /// Average latency in milliseconds
81    pub avg_latency_ms: f64,
82    
83    /// Packet loss rate (0.0 to 1.0)
84    pub packet_loss_rate: f64,
85    
86    /// Current bandwidth usage (bytes per second)
87    pub bandwidth_usage: u64,
88    
89    /// Number of active connections
90    pub active_connections: usize,
91    
92    /// Dummy packet ratio (for traffic shaping analysis)
93    pub dummy_packet_ratio: f64,
94}
95
96impl TransportStats {
97    /// Calculate goodput (actual user data rate, excluding overhead and dummy packets)
98    pub fn goodput(&self) -> f64 {
99        if self.packets_sent == 0 {
100            return 0.0;
101        }
102        
103        let user_data_ratio = 1.0 - self.dummy_packet_ratio;
104        self.bandwidth_usage as f64 * user_data_ratio
105    }
106
107    /// Merge statistics from another transport
108    pub fn merge(&mut self, other: &TransportStats) {
109        self.packets_sent += other.packets_sent;
110        self.packets_received += other.packets_received;
111        self.bytes_sent += other.bytes_sent;
112        self.bytes_received += other.bytes_received;
113        
114        // Weighted average for latency
115        let total_packets = self.packets_sent + other.packets_sent;
116        if total_packets > 0 {
117            self.avg_latency_ms = (self.avg_latency_ms * self.packets_sent as f64
118                + other.avg_latency_ms * other.packets_sent as f64)
119                / total_packets as f64;
120        }
121        
122        // Average packet loss rate
123        self.packet_loss_rate = (self.packet_loss_rate + other.packet_loss_rate) / 2.0;
124        
125        self.bandwidth_usage += other.bandwidth_usage;
126        self.active_connections += other.active_connections;
127    }
128}
129
130/// Configuration for transport behavior
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct TransportConfig {
133    /// Cover protocol to use
134    pub protocol: CoverProtocol,
135    
136    /// Maximum bandwidth in bytes per second
137    pub max_bandwidth: u64,
138    
139    /// Enable dummy traffic generation
140    pub enable_dummy_traffic: bool,
141    
142    /// Target dummy traffic ratio (0.0 to 1.0)
143    pub dummy_traffic_ratio: f64,
144    
145    /// Packet size distribution matching
146    pub match_packet_size_distribution: bool,
147    
148    /// Timing pattern matching
149    pub match_timing_patterns: bool,
150    
151    /// Maximum latency tolerance in milliseconds
152    pub max_latency_ms: u64,
153}
154
155impl Default for TransportConfig {
156    fn default() -> Self {
157        Self {
158            protocol: CoverProtocol::WebRTC,
159            max_bandwidth: 5_000_000, // 5 Mbps
160            enable_dummy_traffic: true,
161            dummy_traffic_ratio: 0.3,
162            match_packet_size_distribution: true,
163            match_timing_patterns: true,
164            max_latency_ms: 500,
165        }
166    }
167}