1pub mod config;
29pub mod error;
30pub mod icmp_state;
31pub mod key;
32pub mod spill;
33pub mod state;
34pub mod table;
35pub mod tcp_reassembly;
36pub mod tcp_state;
37pub mod udp_state;
38
39pub use config::FlowConfig;
41pub use error::FlowError;
42pub use icmp_state::IcmpFlowState;
43pub use key::{
44 CanonicalKey, FlowDirection, TransportProtocol, ZWaveKey, extract_key, extract_zwave_key,
45};
46pub use state::{
47 ConversationState, ConversationStatus, DirectionStats, ProtocolState, ZWaveFlowState,
48};
49pub use table::ConversationTable;
50pub use tcp_reassembly::{ReassemblyAction, TcpReassembler};
51pub use tcp_state::{TcpConnectionState, TcpConversationState, TcpEndpointState};
52pub use udp_state::UdpFlowState;
53
54use std::collections::HashMap;
55use std::path::Path;
56use std::time::Instant;
57
58use crate::error::PacketError;
59use crate::layer::LayerKind;
60use crate::pcap::{CaptureIterator, CapturedPacket};
61
62fn format_bytes(bytes: usize) -> String {
64 const KB: usize = 1024;
65 const MB: usize = 1024 * KB;
66 const GB: usize = 1024 * MB;
67 if bytes >= GB {
68 format!("{:.2} GB", bytes as f64 / GB as f64)
69 } else if bytes >= MB {
70 format!("{:.1} MB", bytes as f64 / MB as f64)
71 } else if bytes >= KB {
72 format!("{:.1} KB", bytes as f64 / KB as f64)
73 } else {
74 format!("{bytes} B")
75 }
76}
77
78fn format_count(n: usize) -> String {
80 let s = n.to_string();
81 let mut result = String::with_capacity(s.len() + s.len() / 3);
82 for (i, c) in s.chars().enumerate() {
83 if i > 0 && (s.len() - i) % 3 == 0 {
84 result.push(',');
85 }
86 result.push(c);
87 }
88 result
89}
90
91fn format_duration(secs: f64) -> String {
93 if secs >= 3600.0 {
94 let h = (secs / 3600.0).floor();
95 let m = ((secs % 3600.0) / 60.0).floor();
96 format!("{h:.0}h {m:.0}m")
97 } else if secs >= 60.0 {
98 let m = (secs / 60.0).floor();
99 let s = secs % 60.0;
100 format!("{m:.0}m {s:.0}s")
101 } else {
102 format!("{secs:.1}s")
103 }
104}
105
106pub fn extract_flows(packets: &[CapturedPacket]) -> Result<Vec<ConversationState>, FlowError> {
115 extract_flows_with_config(packets, FlowConfig::default())
116}
117
118pub fn extract_flows_with_config(
120 packets: &[CapturedPacket],
121 config: FlowConfig,
122) -> Result<Vec<ConversationState>, FlowError> {
123 let verbose = config.verbose;
124 let interval = config.progress_interval.max(1);
125 let total = packets.len();
126 let table = ConversationTable::new(config);
127
128 let wall_start = Instant::now();
129
130 if verbose {
131 eprintln!();
132 eprintln!("[+] stackforge flow extraction engine");
133 eprintln!("[+] Input: {} packets (in-memory)", format_count(total));
134 eprintln!("[+] Processing...");
135 eprintln!();
136 }
137
138 for (index, captured) in packets.iter().enumerate() {
139 let timestamp = captured.metadata.timestamp;
140 table.ingest_packet(&captured.packet, timestamp, index)?;
141
142 if verbose && (index + 1) % interval == 0 {
143 let elapsed = wall_start.elapsed().as_secs_f64();
144 let rate = (index + 1) as f64 / elapsed;
145 let pct = (index + 1) as f64 / total as f64 * 100.0;
146 let remaining = (total - index - 1) as f64 / rate;
147 let mem = table.memory_usage();
148 eprintln!(
149 " [{:5.1}%] {} pkts | {} flows | {}/s | mem ~{} | ETA {}",
150 pct,
151 format_count(index + 1),
152 format_count(table.conversation_count()),
153 format_count(rate as usize),
154 format_bytes(mem),
155 format_duration(remaining),
156 );
157 }
158 }
159
160 if verbose {
161 eprintln!();
162 }
163 let conversations = table.into_conversations();
164 if verbose {
165 let elapsed = wall_start.elapsed().as_secs_f64();
166 let rate = total as f64 / elapsed;
167 eprintln!(
168 "[+] Complete: {} packets -> {} flows",
169 format_count(total),
170 format_count(conversations.len())
171 );
172 eprintln!(
173 "[+] Wall time: {} ({}/s avg)",
174 format_duration(elapsed),
175 format_count(rate as usize)
176 );
177
178 let (total_drops, flows_with_drops) = count_dropped_segments(&conversations);
179 if total_drops > 0 {
180 eprintln!(
181 "[!] Warning: {} TCP segments dropped across {} flows (buffer/fragment limits exceeded)",
182 format_count(total_drops as usize),
183 format_count(flows_with_drops),
184 );
185 eprintln!(
186 "[!] Tip: increase max_reassembly_buffer or max_ooo_fragments to capture more data"
187 );
188 }
189 eprintln!();
190 }
191 Ok(conversations)
192}
193
194pub fn extract_flows_streaming<I>(
203 packets: I,
204 config: FlowConfig,
205) -> Result<Vec<ConversationState>, FlowError>
206where
207 I: Iterator<Item = Result<CapturedPacket, PacketError>>,
208{
209 let verbose = config.verbose;
210 let interval = config.progress_interval.max(1);
211 let has_budget = config.memory_budget.is_some();
212 let budget_str = config
213 .memory_budget
214 .map(|b| format_bytes(b))
215 .unwrap_or_else(|| "unlimited".to_string());
216 let table = ConversationTable::new(config);
217
218 let wall_start = Instant::now();
219
220 if verbose {
221 eprintln!();
222 eprintln!("[+] stackforge flow extraction engine");
223 eprintln!("[+] Mode: streaming (packets read from disk on-the-fly)");
224 if has_budget {
225 eprintln!("[+] Memory budget: {budget_str}");
226 }
227 eprintln!("[+] Processing...");
228 eprintln!();
229 }
230
231 let mut last_report = Instant::now();
232
233 for (index, result) in packets.enumerate() {
234 let captured = result.map_err(FlowError::PacketError)?;
235 let timestamp = captured.metadata.timestamp;
236 table.ingest_packet(&captured.packet, timestamp, index)?;
237 if verbose && (index + 1) % interval == 0 {
240 let now = Instant::now();
241 let elapsed = wall_start.elapsed().as_secs_f64();
242 let delta = now.duration_since(last_report).as_secs_f64();
243 let overall_rate = (index + 1) as f64 / elapsed;
244 let interval_rate = interval as f64 / delta;
245 let mem = table.memory_usage();
246 let spill_note = if has_budget && table.spill_count() > 0 {
247 format!(" | {} spills", format_count(table.spill_count()))
248 } else {
249 String::new()
250 };
251 eprintln!(
252 " [{}] {} pkts | {} flows | {}/s (avg {}/s) | mem ~{}{}",
253 format_duration(elapsed),
254 format_count(index + 1),
255 format_count(table.conversation_count()),
256 format_count(interval_rate as usize),
257 format_count(overall_rate as usize),
258 format_bytes(mem),
259 spill_note,
260 );
261 last_report = now;
262 }
263 }
264
265 if verbose {
266 eprintln!();
267 eprintln!(
268 "[+] Finalizing (sorting {} flows)...",
269 format_count(table.conversation_count())
270 );
271 }
272 let conversations = table.into_conversations();
273 if verbose {
274 let elapsed = wall_start.elapsed().as_secs_f64();
275 eprintln!(
276 "[+] Complete: {} flows extracted",
277 format_count(conversations.len())
278 );
279 eprintln!("[+] Wall time: {}", format_duration(elapsed));
280
281 let (total_drops, flows_with_drops) = count_dropped_segments(&conversations);
283 if total_drops > 0 {
284 eprintln!(
285 "[!] Warning: {} TCP segments dropped across {} flows (buffer/fragment limits exceeded)",
286 format_count(total_drops as usize),
287 format_count(flows_with_drops),
288 );
289 eprintln!(
290 "[!] Tip: increase max_reassembly_buffer or max_ooo_fragments to capture more data"
291 );
292 }
293 eprintln!();
294 }
295 Ok(conversations)
296}
297
298fn count_dropped_segments(conversations: &[ConversationState]) -> (u64, usize) {
300 let mut total_drops: u64 = 0;
301 let mut flows_with_drops: usize = 0;
302 for conv in conversations {
303 if let ProtocolState::Tcp(ref tcp) = conv.protocol_state {
304 let drops = tcp.total_dropped_segments();
305 if drops > 0 {
306 total_drops += drops;
307 flows_with_drops += 1;
308 }
309 }
310 }
311 (total_drops, flows_with_drops)
312}
313
314pub fn extract_flows_from_file(
319 path: impl AsRef<Path>,
320 config: FlowConfig,
321) -> Result<Vec<ConversationState>, FlowError> {
322 let verbose = config.verbose;
323 let file_path = path.as_ref();
324 if verbose {
325 let file_size = std::fs::metadata(file_path)
326 .map(|m| format_bytes(m.len() as usize))
327 .unwrap_or_else(|_| "unknown".to_string());
328 eprintln!("[+] File: {} ({})", file_path.display(), file_size);
329 }
330 let iter = CaptureIterator::open(file_path).map_err(FlowError::PacketError)?;
331 extract_flows_streaming(iter, config)
332}
333
334pub fn extract_zwave_flows(
342 packets: &[CapturedPacket],
343) -> Result<Vec<ConversationState>, FlowError> {
344 let mut conversations: HashMap<ZWaveKey, ConversationState> = HashMap::new();
345
346 for (index, captured) in packets.iter().enumerate() {
347 let timestamp = captured.metadata.timestamp;
348 let packet = &captured.packet;
349
350 if packet.get_layer(LayerKind::ZWave).is_none() {
352 continue;
353 }
354
355 let (key, direction) = match extract_zwave_key(packet) {
356 Ok(result) => result,
357 Err(_) => continue,
358 };
359
360 let byte_count = packet.as_bytes().len() as u64;
361 let buf = packet.as_bytes();
362
363 let conv = conversations.entry(key.clone()).or_insert_with(|| {
364 let mut state = ConversationState::new_zwave(key, timestamp);
365 if let ProtocolState::ZWave(ref mut zw) = state.protocol_state
366 && let Some(zwave) = packet.zwave()
367 {
368 zw.home_id = zwave.home_id(buf).unwrap_or(0);
369 }
370 state
371 });
372
373 conv.record_packet(direction, byte_count, timestamp, index, false, false, true);
374
375 if let ProtocolState::ZWave(ref mut zw) = conv.protocol_state
377 && let Some(zwave) = packet.zwave()
378 {
379 if zwave.is_ack(buf) {
380 zw.ack_count += 1;
381 } else {
382 zw.command_count += 1;
383 }
384 }
385 }
386
387 let mut result: Vec<ConversationState> = conversations.into_values().collect();
388 result.sort_by_key(|c| c.start_time);
389 Ok(result)
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use crate::layer::stack::{LayerStack, LayerStackEntry};
396 use crate::pcap::PcapMetadata;
397 use crate::{EthernetBuilder, Ipv4Builder, MacAddress, Packet, TcpBuilder, UdpBuilder};
398 use std::net::Ipv4Addr;
399 use std::time::Duration;
400
401 fn make_captured(packet: Packet, timestamp_secs: u64) -> CapturedPacket {
402 CapturedPacket {
403 packet,
404 metadata: PcapMetadata {
405 timestamp: Duration::from_secs(timestamp_secs),
406 orig_len: 0,
407 ..Default::default()
408 },
409 }
410 }
411
412 fn tcp_packet(
413 src_ip: Ipv4Addr,
414 dst_ip: Ipv4Addr,
415 sport: u16,
416 dport: u16,
417 flags: &str,
418 ) -> Packet {
419 let mut builder = TcpBuilder::new()
420 .src_port(sport)
421 .dst_port(dport)
422 .seq(1000)
423 .ack_num(0)
424 .window(65535);
425
426 for c in flags.chars() {
427 builder = match c {
428 'S' => builder.syn(),
429 'A' => builder.ack(),
430 'F' => builder.fin(),
431 'R' => builder.rst(),
432 _ => builder,
433 };
434 }
435
436 LayerStack::new()
437 .push(LayerStackEntry::Ethernet(
438 EthernetBuilder::new()
439 .dst(MacAddress::BROADCAST)
440 .src(MacAddress::new([0, 1, 2, 3, 4, 5])),
441 ))
442 .push(LayerStackEntry::Ipv4(
443 Ipv4Builder::new().src(src_ip).dst(dst_ip),
444 ))
445 .push(LayerStackEntry::Tcp(builder))
446 .build_packet()
447 }
448
449 fn udp_packet(src_ip: Ipv4Addr, dst_ip: Ipv4Addr, sport: u16, dport: u16) -> Packet {
450 LayerStack::new()
451 .push(LayerStackEntry::Ethernet(
452 EthernetBuilder::new()
453 .dst(MacAddress::BROADCAST)
454 .src(MacAddress::new([0, 1, 2, 3, 4, 5])),
455 ))
456 .push(LayerStackEntry::Ipv4(
457 Ipv4Builder::new().src(src_ip).dst(dst_ip),
458 ))
459 .push(LayerStackEntry::Udp(
460 UdpBuilder::new().src_port(sport).dst_port(dport),
461 ))
462 .build_packet()
463 }
464
465 #[test]
466 fn test_extract_flows_empty() {
467 let result = extract_flows(&[]).unwrap();
468 assert!(result.is_empty());
469 }
470
471 #[test]
472 fn test_extract_flows_single_tcp() {
473 let packets = vec![
474 make_captured(
475 tcp_packet(
476 Ipv4Addr::new(10, 0, 0, 1),
477 Ipv4Addr::new(10, 0, 0, 2),
478 12345,
479 80,
480 "S",
481 ),
482 1,
483 ),
484 make_captured(
485 tcp_packet(
486 Ipv4Addr::new(10, 0, 0, 2),
487 Ipv4Addr::new(10, 0, 0, 1),
488 80,
489 12345,
490 "SA",
491 ),
492 2,
493 ),
494 ];
495
496 let conversations = extract_flows(&packets).unwrap();
497 assert_eq!(conversations.len(), 1);
498 assert_eq!(conversations[0].total_packets(), 2);
499 assert_eq!(conversations[0].key.protocol, TransportProtocol::Tcp);
500 }
501
502 #[test]
503 fn test_extract_flows_multiple_conversations() {
504 let packets = vec![
505 make_captured(
506 tcp_packet(
507 Ipv4Addr::new(10, 0, 0, 1),
508 Ipv4Addr::new(10, 0, 0, 2),
509 12345,
510 80,
511 "S",
512 ),
513 1,
514 ),
515 make_captured(
516 udp_packet(
517 Ipv4Addr::new(10, 0, 0, 1),
518 Ipv4Addr::new(10, 0, 0, 3),
519 54321,
520 53,
521 ),
522 2,
523 ),
524 make_captured(
525 tcp_packet(
526 Ipv4Addr::new(10, 0, 0, 2),
527 Ipv4Addr::new(10, 0, 0, 1),
528 80,
529 12345,
530 "SA",
531 ),
532 3,
533 ),
534 ];
535
536 let conversations = extract_flows(&packets).unwrap();
537 assert_eq!(conversations.len(), 2);
538 assert!(conversations[0].start_time <= conversations[1].start_time);
540 }
541
542 #[test]
543 fn test_extract_flows_preserves_packet_indices() {
544 let packets = vec![
545 make_captured(
546 tcp_packet(
547 Ipv4Addr::new(10, 0, 0, 1),
548 Ipv4Addr::new(10, 0, 0, 2),
549 12345,
550 80,
551 "S",
552 ),
553 1,
554 ),
555 make_captured(
556 tcp_packet(
557 Ipv4Addr::new(10, 0, 0, 2),
558 Ipv4Addr::new(10, 0, 0, 1),
559 80,
560 12345,
561 "SA",
562 ),
563 2,
564 ),
565 ];
566
567 let conversations = extract_flows(&packets).unwrap();
568 assert_eq!(conversations[0].packet_indices, vec![0, 1]);
569 }
570}