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 eprintln!();
178 }
179 Ok(conversations)
180}
181
182pub fn extract_flows_streaming<I>(
191 packets: I,
192 config: FlowConfig,
193) -> Result<Vec<ConversationState>, FlowError>
194where
195 I: Iterator<Item = Result<CapturedPacket, PacketError>>,
196{
197 let verbose = config.verbose;
198 let interval = config.progress_interval.max(1);
199 let has_budget = config.memory_budget.is_some();
200 let budget_str = config
201 .memory_budget
202 .map(|b| format_bytes(b))
203 .unwrap_or_else(|| "unlimited".to_string());
204 let table = ConversationTable::new(config);
205
206 let wall_start = Instant::now();
207
208 if verbose {
209 eprintln!();
210 eprintln!("[+] stackforge flow extraction engine");
211 eprintln!("[+] Mode: streaming (packets read from disk on-the-fly)");
212 if has_budget {
213 eprintln!("[+] Memory budget: {budget_str}");
214 }
215 eprintln!("[+] Processing...");
216 eprintln!();
217 }
218
219 let mut last_report = Instant::now();
220
221 for (index, result) in packets.enumerate() {
222 let captured = result.map_err(FlowError::PacketError)?;
223 let timestamp = captured.metadata.timestamp;
224 table.ingest_packet(&captured.packet, timestamp, index)?;
225 if verbose && (index + 1) % interval == 0 {
228 let now = Instant::now();
229 let elapsed = wall_start.elapsed().as_secs_f64();
230 let delta = now.duration_since(last_report).as_secs_f64();
231 let overall_rate = (index + 1) as f64 / elapsed;
232 let interval_rate = interval as f64 / delta;
233 let mem = table.memory_usage();
234 let spill_note = if has_budget && table.spill_count() > 0 {
235 format!(" | {} spills", format_count(table.spill_count()))
236 } else {
237 String::new()
238 };
239 eprintln!(
240 " [{}] {} pkts | {} flows | {}/s (avg {}/s) | mem ~{}{}",
241 format_duration(elapsed),
242 format_count(index + 1),
243 format_count(table.conversation_count()),
244 format_count(interval_rate as usize),
245 format_count(overall_rate as usize),
246 format_bytes(mem),
247 spill_note,
248 );
249 last_report = now;
250 }
251 }
252
253 if verbose {
254 eprintln!();
255 eprintln!(
256 "[+] Finalizing (sorting {} flows)...",
257 format_count(table.conversation_count())
258 );
259 }
260 let conversations = table.into_conversations();
261 if verbose {
262 let elapsed = wall_start.elapsed().as_secs_f64();
263 eprintln!(
264 "[+] Complete: {} flows extracted",
265 format_count(conversations.len())
266 );
267 eprintln!("[+] Wall time: {}", format_duration(elapsed));
268 eprintln!();
269 }
270 Ok(conversations)
271}
272
273pub fn extract_flows_from_file(
278 path: impl AsRef<Path>,
279 config: FlowConfig,
280) -> Result<Vec<ConversationState>, FlowError> {
281 let verbose = config.verbose;
282 let file_path = path.as_ref();
283 if verbose {
284 let file_size = std::fs::metadata(file_path)
285 .map(|m| format_bytes(m.len() as usize))
286 .unwrap_or_else(|_| "unknown".to_string());
287 eprintln!("[+] File: {} ({})", file_path.display(), file_size);
288 }
289 let iter = CaptureIterator::open(file_path).map_err(FlowError::PacketError)?;
290 extract_flows_streaming(iter, config)
291}
292
293pub fn extract_zwave_flows(
301 packets: &[CapturedPacket],
302) -> Result<Vec<ConversationState>, FlowError> {
303 let mut conversations: HashMap<ZWaveKey, ConversationState> = HashMap::new();
304
305 for (index, captured) in packets.iter().enumerate() {
306 let timestamp = captured.metadata.timestamp;
307 let packet = &captured.packet;
308
309 if packet.get_layer(LayerKind::ZWave).is_none() {
311 continue;
312 }
313
314 let (key, direction) = match extract_zwave_key(packet) {
315 Ok(result) => result,
316 Err(_) => continue,
317 };
318
319 let byte_count = packet.as_bytes().len() as u64;
320 let buf = packet.as_bytes();
321
322 let conv = conversations.entry(key.clone()).or_insert_with(|| {
323 let mut state = ConversationState::new_zwave(key, timestamp);
324 if let ProtocolState::ZWave(ref mut zw) = state.protocol_state
325 && let Some(zwave) = packet.zwave()
326 {
327 zw.home_id = zwave.home_id(buf).unwrap_or(0);
328 }
329 state
330 });
331
332 conv.record_packet(direction, byte_count, timestamp, index, false, false, true);
333
334 if let ProtocolState::ZWave(ref mut zw) = conv.protocol_state
336 && let Some(zwave) = packet.zwave()
337 {
338 if zwave.is_ack(buf) {
339 zw.ack_count += 1;
340 } else {
341 zw.command_count += 1;
342 }
343 }
344 }
345
346 let mut result: Vec<ConversationState> = conversations.into_values().collect();
347 result.sort_by_key(|c| c.start_time);
348 Ok(result)
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354 use crate::layer::stack::{LayerStack, LayerStackEntry};
355 use crate::pcap::PcapMetadata;
356 use crate::{EthernetBuilder, Ipv4Builder, MacAddress, Packet, TcpBuilder, UdpBuilder};
357 use std::net::Ipv4Addr;
358 use std::time::Duration;
359
360 fn make_captured(packet: Packet, timestamp_secs: u64) -> CapturedPacket {
361 CapturedPacket {
362 packet,
363 metadata: PcapMetadata {
364 timestamp: Duration::from_secs(timestamp_secs),
365 orig_len: 0,
366 ..Default::default()
367 },
368 }
369 }
370
371 fn tcp_packet(
372 src_ip: Ipv4Addr,
373 dst_ip: Ipv4Addr,
374 sport: u16,
375 dport: u16,
376 flags: &str,
377 ) -> Packet {
378 let mut builder = TcpBuilder::new()
379 .src_port(sport)
380 .dst_port(dport)
381 .seq(1000)
382 .ack_num(0)
383 .window(65535);
384
385 for c in flags.chars() {
386 builder = match c {
387 'S' => builder.syn(),
388 'A' => builder.ack(),
389 'F' => builder.fin(),
390 'R' => builder.rst(),
391 _ => builder,
392 };
393 }
394
395 LayerStack::new()
396 .push(LayerStackEntry::Ethernet(
397 EthernetBuilder::new()
398 .dst(MacAddress::BROADCAST)
399 .src(MacAddress::new([0, 1, 2, 3, 4, 5])),
400 ))
401 .push(LayerStackEntry::Ipv4(
402 Ipv4Builder::new().src(src_ip).dst(dst_ip),
403 ))
404 .push(LayerStackEntry::Tcp(builder))
405 .build_packet()
406 }
407
408 fn udp_packet(src_ip: Ipv4Addr, dst_ip: Ipv4Addr, sport: u16, dport: u16) -> Packet {
409 LayerStack::new()
410 .push(LayerStackEntry::Ethernet(
411 EthernetBuilder::new()
412 .dst(MacAddress::BROADCAST)
413 .src(MacAddress::new([0, 1, 2, 3, 4, 5])),
414 ))
415 .push(LayerStackEntry::Ipv4(
416 Ipv4Builder::new().src(src_ip).dst(dst_ip),
417 ))
418 .push(LayerStackEntry::Udp(
419 UdpBuilder::new().src_port(sport).dst_port(dport),
420 ))
421 .build_packet()
422 }
423
424 #[test]
425 fn test_extract_flows_empty() {
426 let result = extract_flows(&[]).unwrap();
427 assert!(result.is_empty());
428 }
429
430 #[test]
431 fn test_extract_flows_single_tcp() {
432 let packets = vec![
433 make_captured(
434 tcp_packet(
435 Ipv4Addr::new(10, 0, 0, 1),
436 Ipv4Addr::new(10, 0, 0, 2),
437 12345,
438 80,
439 "S",
440 ),
441 1,
442 ),
443 make_captured(
444 tcp_packet(
445 Ipv4Addr::new(10, 0, 0, 2),
446 Ipv4Addr::new(10, 0, 0, 1),
447 80,
448 12345,
449 "SA",
450 ),
451 2,
452 ),
453 ];
454
455 let conversations = extract_flows(&packets).unwrap();
456 assert_eq!(conversations.len(), 1);
457 assert_eq!(conversations[0].total_packets(), 2);
458 assert_eq!(conversations[0].key.protocol, TransportProtocol::Tcp);
459 }
460
461 #[test]
462 fn test_extract_flows_multiple_conversations() {
463 let packets = vec![
464 make_captured(
465 tcp_packet(
466 Ipv4Addr::new(10, 0, 0, 1),
467 Ipv4Addr::new(10, 0, 0, 2),
468 12345,
469 80,
470 "S",
471 ),
472 1,
473 ),
474 make_captured(
475 udp_packet(
476 Ipv4Addr::new(10, 0, 0, 1),
477 Ipv4Addr::new(10, 0, 0, 3),
478 54321,
479 53,
480 ),
481 2,
482 ),
483 make_captured(
484 tcp_packet(
485 Ipv4Addr::new(10, 0, 0, 2),
486 Ipv4Addr::new(10, 0, 0, 1),
487 80,
488 12345,
489 "SA",
490 ),
491 3,
492 ),
493 ];
494
495 let conversations = extract_flows(&packets).unwrap();
496 assert_eq!(conversations.len(), 2);
497 assert!(conversations[0].start_time <= conversations[1].start_time);
499 }
500
501 #[test]
502 fn test_extract_flows_preserves_packet_indices() {
503 let packets = vec![
504 make_captured(
505 tcp_packet(
506 Ipv4Addr::new(10, 0, 0, 1),
507 Ipv4Addr::new(10, 0, 0, 2),
508 12345,
509 80,
510 "S",
511 ),
512 1,
513 ),
514 make_captured(
515 tcp_packet(
516 Ipv4Addr::new(10, 0, 0, 2),
517 Ipv4Addr::new(10, 0, 0, 1),
518 80,
519 12345,
520 "SA",
521 ),
522 2,
523 ),
524 ];
525
526 let conversations = extract_flows(&packets).unwrap();
527 assert_eq!(conversations[0].packet_indices, vec![0, 1]);
528 }
529}