use log::{debug, warn};
use std::fmt::Debug;
use std::time::{Duration, SystemTime};
use crate::network::dpi::{DpiResult, is_partial_sni, try_extract_tls_from_reassembler};
use crate::network::parser::{ParsedPacket, SynWindowScale, TcpFlags, TcpHeaderInfo};
use crate::network::types::{
ApplicationProtocol, Connection, DnsInfo, DpiInfo, FtpInfo, HttpInfo, MqttInfo, NetBiosInfo,
ProtocolState, QuicConnectionState, QuicInfo, SshInfo, TcpState, TlsInfo,
};
const MAX_MERGED_RESPONSE_IPS: usize = 64;
fn update_tcp_state(current_state: TcpState, flags: &TcpFlags, is_outgoing: bool) -> TcpState {
debug!(
"Updating TCP state: current_state={:?}, flags={:?}, is_outgoing={}",
current_state, flags, is_outgoing
);
match (current_state, flags.syn, flags.ack, flags.fin, flags.rst) {
(TcpState::Unknown, true, false, false, false) if !is_outgoing => TcpState::SynReceived,
(TcpState::Unknown, true, false, false, false) if is_outgoing => TcpState::SynSent,
(TcpState::SynSent, true, true, false, false) if !is_outgoing => TcpState::Established,
(TcpState::SynReceived, false, true, false, false) if is_outgoing => TcpState::Established,
(TcpState::Unknown, false, true, false, false) => TcpState::Established,
(TcpState::Unknown, false, true, true, false) => TcpState::Established,
(TcpState::Established, false, _, true, false) if is_outgoing => TcpState::FinWait1,
(TcpState::Established, false, _, true, false) if !is_outgoing => TcpState::CloseWait,
(TcpState::FinWait1, false, true, false, false) if !is_outgoing => TcpState::FinWait2,
(TcpState::FinWait1, false, _, true, false) if !is_outgoing => TcpState::Closing,
(TcpState::FinWait2, false, _, true, false) if !is_outgoing => TcpState::TimeWait,
(TcpState::CloseWait, false, _, true, false) if is_outgoing => TcpState::LastAck,
(TcpState::LastAck, false, true, false, false) if !is_outgoing => TcpState::Closed,
(TcpState::Closing, false, true, false, false) if !is_outgoing => TcpState::TimeWait,
(_, _, _, _, true) => TcpState::Closed,
_ => current_state,
}
}
fn seq_lt(a: u32, b: u32) -> bool {
(a.wrapping_sub(b) as i32) < 0
}
#[derive(Debug, Default, Clone, Copy)]
pub struct TcpMergeEvents {
pub retransmits: u64,
pub out_of_order: u64,
pub fast_retransmits: u64,
pub rtt_sample: Option<Duration>,
}
const RTT_PROBE_TIMEOUT: Duration = Duration::from_secs(10);
struct TcpSegment {
seq: u32,
ack: u32,
window: u16,
payload_len: u32,
is_outgoing: bool,
has_ack_flag: bool,
is_syn: bool,
is_rst: bool,
window_scale: Option<SynWindowScale>,
}
fn tcp_segment_from(parsed: &ParsedPacket, tcp_header: &TcpHeaderInfo) -> TcpSegment {
TcpSegment {
seq: tcp_header.seq,
ack: tcp_header.ack,
window: tcp_header.window,
payload_len: tcp_header.payload_len
+ u32::from(tcp_header.flags.syn)
+ u32::from(tcp_header.flags.fin),
is_outgoing: parsed.is_outgoing,
has_ack_flag: tcp_header.flags.ack,
is_syn: tcp_header.flags.syn,
is_rst: tcp_header.flags.rst,
window_scale: tcp_header.window_scale,
}
}
fn analyze_tcp_segment(
analytics: &mut crate::network::types::TcpAnalytics,
segment: TcpSegment,
at: SystemTime,
) -> TcpMergeEvents {
let TcpSegment {
seq,
ack,
window,
payload_len,
is_outgoing,
has_ack_flag,
is_syn,
is_rst,
window_scale,
} = segment;
let mut events = TcpMergeEvents::default();
let previous_window_in = analytics.last_window_in;
if is_syn {
match window_scale {
Some(SynWindowScale::Present(shift)) => {
if is_outgoing {
analytics.window_scale_out = Some(shift);
} else {
analytics.window_scale_in = Some(shift);
}
}
Some(SynWindowScale::Absent) => analytics.window_scaling_disabled = true,
Some(SynWindowScale::Unknown) | None => {}
}
}
if !is_rst {
analytics.record_window(window, is_outgoing, is_syn);
}
if is_outgoing {
if payload_len > 0 {
let seq_end = seq.wrapping_add(payload_len);
if !analytics.seen_outbound {
analytics.seen_outbound = true;
analytics.highest_seq_outbound = seq_end;
arm_rtt_probe(analytics, seq_end, at);
} else if !seq_lt(analytics.highest_seq_outbound, seq_end) {
analytics.retransmit_count += 1;
events.retransmits += 1;
analytics.rtt_probe = None;
debug!(
"TCP retransmission detected: seq={}, len={}, highest={}",
seq, payload_len, analytics.highest_seq_outbound
);
} else {
analytics.highest_seq_outbound = seq_end;
arm_rtt_probe(analytics, seq_end, at);
}
}
} else {
if payload_len > 0 {
let seq_end = seq.wrapping_add(payload_len);
if !analytics.seen_inbound {
analytics.seen_inbound = true;
analytics.highest_seq_inbound = seq_end;
} else if !seq_lt(analytics.highest_seq_inbound, seq_end) {
analytics.out_of_order_count += 1;
events.out_of_order += 1;
debug!(
"TCP out-of-order packet: seq={}, len={}, highest={}",
seq, payload_len, analytics.highest_seq_inbound
);
} else {
analytics.highest_seq_inbound = seq_end;
}
}
if has_ack_flag
&& let Some((probe_seq, sent_at)) = analytics.rtt_probe
&& !seq_lt(ack, probe_seq)
{
if let Ok(rtt) = at.duration_since(sent_at) {
analytics.smoothed_rtt = Some(match analytics.smoothed_rtt {
Some(srtt) => (srtt * 7 + rtt) / 8,
None => rtt,
});
events.rtt_sample = Some(rtt);
}
analytics.rtt_probe = None;
}
if has_ack_flag && payload_len == 0 {
let data_outstanding =
analytics.seen_outbound && seq_lt(ack, analytics.highest_seq_outbound);
let window_unchanged = previous_window_in.is_none_or(|prev| prev.raw == window);
if !analytics.seen_ack {
analytics.seen_ack = true;
analytics.last_ack_received = ack;
} else if ack == analytics.last_ack_received {
if data_outstanding && window_unchanged {
analytics.dup_ack_run += 1;
analytics.duplicate_ack_count += 1;
if analytics.dup_ack_run == 3 {
analytics.fast_retransmit_count += 1;
events.fast_retransmits += 1;
debug!("TCP fast retransmit triggered (3 duplicate ACKs)");
}
}
} else if seq_lt(analytics.last_ack_received, ack) {
analytics.last_ack_received = ack;
analytics.dup_ack_run = 0;
}
}
}
events
}
fn arm_rtt_probe(
analytics: &mut crate::network::types::TcpAnalytics,
seq_end: u32,
at: SystemTime,
) {
let stale = analytics.rtt_probe.is_none_or(|(_, sent_at)| {
at.duration_since(sent_at)
.map_or(true, |age| age > RTT_PROBE_TIMEOUT)
});
if stale {
analytics.rtt_probe = Some((seq_end, at));
}
}
pub fn merge_packet_into_connection(
conn: &mut Connection,
parsed: &ParsedPacket,
now: SystemTime,
) -> TcpMergeEvents {
let tcp_events = apply_packet(conn, parsed, now);
update_connection_rates(conn);
tcp_events
}
fn apply_packet(conn: &mut Connection, parsed: &ParsedPacket, now: SystemTime) -> TcpMergeEvents {
let mut tcp_events = TcpMergeEvents::default();
let was_terminal = conn.is_terminal();
let observation_time = conn.last_activity.max(now);
conn.last_activity = observation_time;
conn.local_addr_kind = parsed.local_addr_kind;
conn.remote_addr_kind = parsed.remote_addr_kind;
conn.remote_is_gateway = parsed.remote_is_gateway;
if let Some(vlan_id) = parsed.vlan_id.filter(|id| *id <= 0x0fff)
&& let Err(index) = conn.observed_vlan_ids.binary_search(&vlan_id)
{
conn.observed_vlan_ids.insert(index, vlan_id);
}
if parsed.is_outgoing {
conn.packets_sent += 1;
conn.bytes_sent += parsed.packet_len as u64;
} else {
conn.packets_received += 1;
conn.bytes_received += parsed.packet_len as u64;
}
if let Some(tcp_header) = parsed.tcp_header {
let current_tcp_state = match conn.protocol_state {
ProtocolState::Tcp(state) => state,
_ => {
warn!("Merging TCP packet into non-TCP connection, resetting to Unknown state");
TcpState::Unknown
}
};
let new_tcp_state =
update_tcp_state(current_tcp_state, &tcp_header.flags, parsed.is_outgoing);
if current_tcp_state != new_tcp_state {
debug!(
"TCP state transition: {:?} -> {:?}",
current_tcp_state, new_tcp_state
);
}
conn.protocol_state = ProtocolState::Tcp(new_tcp_state);
if let Some(analytics) = conn.tcp_analytics.as_mut() {
tcp_events = analyze_tcp_segment(analytics, tcp_segment_from(parsed, &tcp_header), now);
}
} else {
match (&conn.protocol_state, &parsed.protocol_state) {
(ProtocolState::Tcp(_), _) => {
}
_ => {
conn.protocol_state = parsed.protocol_state.clone();
}
}
if conn.connection_direction.is_none() {
conn.connection_direction = icmp_echo_direction(parsed);
}
}
if let Some(dpi_result) = &parsed.dpi_result {
merge_dpi_info(conn, dpi_result);
}
if let Some(new_process_name) = &parsed.process_name {
adopt_immutable(
conn,
|c| &mut c.process_name,
new_process_name,
"process name",
);
}
if let Some(new_pid) = parsed.process_id {
adopt_immutable(conn, |c| &mut c.pid, &new_pid, "PID");
}
let is_terminal = conn.is_terminal();
if is_terminal {
if !was_terminal || conn.terminal_since.is_none() {
conn.terminal_since = Some(observation_time);
}
} else {
conn.terminal_since = None;
}
tcp_events
}
fn adopt_immutable<T: PartialEq + Clone + Debug>(
conn: &mut Connection,
slot: fn(&mut Connection) -> &mut Option<T>,
new: &T,
what: &str,
) {
match slot(conn) {
None => {
*slot(conn) = Some(new.clone());
debug!(
"🔒 Set IMMUTABLE {} for connection {} from PKTAP: {:?}",
what,
conn.key(),
new
);
}
Some(existing) if existing != new => {
let existing = existing.clone();
warn!(
"🚫 IMMUTABILITY VIOLATION: Attempt to change {} for {} from {:?} to {:?} - REJECTED",
what,
conn.key(),
existing,
new
);
}
Some(_) => {
debug!(
"✅ {} confirmed unchanged for {}: {:?}",
what,
conn.key(),
new
);
}
}
}
fn icmp_echo_direction(parsed: &ParsedPacket) -> Option<bool> {
match parsed.protocol_state {
ProtocolState::Icmp {
icmp_type: 8 | 128,
icmp_id: Some(_),
..
} => Some(parsed.is_outgoing),
_ => None,
}
}
pub(crate) fn create_connection_from_packet(parsed: &ParsedPacket, now: SystemTime) -> Connection {
let initial_state = if parsed.tcp_header.is_some() {
ProtocolState::Tcp(TcpState::Unknown)
} else {
parsed.protocol_state.clone()
};
let mut conn = Connection::new(
parsed.protocol,
parsed.local_addr,
parsed.remote_addr,
initial_state,
);
conn.created_at = now;
conn.last_activity = now;
apply_packet(&mut conn, parsed, now);
if let Some(tcp_header) = parsed.tcp_header
&& let ProtocolState::Tcp(tcp_state) = conn.protocol_state
{
conn.connection_direction = match tcp_state {
TcpState::SynSent => Some(true), TcpState::SynReceived => Some(false), _ => {
if tcp_header.flags.syn && tcp_header.flags.ack {
Some(!parsed.is_outgoing)
} else {
None }
}
};
debug!(
"Created new {} connection: {:?} -> {:?}, state: {:?}, direction: {:?}",
parsed.protocol,
parsed.local_addr,
parsed.remote_addr,
conn.protocol_state,
conn.connection_direction
);
}
conn.rate_tracker
.initialize_with_counts(conn.bytes_sent, conn.bytes_received);
conn
}
fn merge_dpi_info(conn: &mut Connection, dpi_result: &DpiResult) {
match &mut conn.dpi_info {
None => {
conn.dpi_info = Some(DpiInfo {
application: dpi_result.application.clone(),
});
debug!(
"Added DPI info to connection: {} - {}",
conn.key(),
dpi_result.application
);
}
Some(dpi_info) => {
match (&mut dpi_info.application, &dpi_result.application) {
(ApplicationProtocol::Http(old_info), ApplicationProtocol::Http(new_info)) => {
merge_http_info(old_info, new_info);
}
(ApplicationProtocol::Https(old_info), ApplicationProtocol::Https(new_info)) => {
merge_tls_info(&mut old_info.tls_info, &new_info.tls_info);
}
(ApplicationProtocol::Quic(old_info), ApplicationProtocol::Quic(new_info)) => {
merge_quic_info(old_info.as_mut(), new_info.as_ref());
}
(ApplicationProtocol::Dns(old_info), ApplicationProtocol::Dns(new_info)) => {
merge_dns_info(old_info, new_info);
}
(
ApplicationProtocol::NetBios(old_info),
ApplicationProtocol::NetBios(new_info),
) => {
merge_netbios_info(old_info, new_info);
}
(ApplicationProtocol::Ssh(old_info), ApplicationProtocol::Ssh(new_info)) => {
merge_ssh_info(old_info, new_info);
}
(
ApplicationProtocol::BitTorrent(old_info),
ApplicationProtocol::BitTorrent(new_info),
) => {
set_if_absent(&mut old_info.client, &new_info.client);
set_if_absent(&mut old_info.info_hash, &new_info.info_hash);
}
(ApplicationProtocol::Mqtt(old_info), ApplicationProtocol::Mqtt(new_info)) => {
merge_mqtt_info(old_info, new_info);
}
(ApplicationProtocol::Ftp(old_info), ApplicationProtocol::Ftp(new_info)) => {
merge_ftp_info(old_info, new_info);
}
(ApplicationProtocol::MySql(old), ApplicationProtocol::MySql(new)) => {
set_if_absent(&mut old.server_version, &new.server_version);
set_if_absent(&mut old.connection_id, &new.connection_id);
set_if_absent(&mut old.tls_supported, &new.tls_supported);
old.tls_requested |= new.tls_requested;
merge_tls_info(&mut old.tls_info, &new.tls_info);
}
(ApplicationProtocol::Redis(old), ApplicationProtocol::Redis(new)) => {
old.command.clone_from(&new.command);
overwrite_if_present(&mut old.requested_version, &new.requested_version);
overwrite_if_present(&mut old.requested_database, &new.requested_database);
}
(ApplicationProtocol::PostgreSql(old), ApplicationProtocol::PostgreSql(new)) => {
set_if_absent(&mut old.protocol_minor, &new.protocol_minor);
set_if_absent(&mut old.database, &new.database);
set_if_absent(&mut old.application_name, &new.application_name);
old.tls_requested |= new.tls_requested;
merge_tls_info(&mut old.tls_info, &new.tls_info);
}
(ApplicationProtocol::MySql(old), ApplicationProtocol::Https(new)) => {
merge_tls_info(&mut old.tls_info, &new.tls_info);
}
(ApplicationProtocol::PostgreSql(old), ApplicationProtocol::Https(new)) => {
merge_tls_info(&mut old.tls_info, &new.tls_info);
}
_ => {
}
}
}
}
}
fn set_if_absent<T: Clone>(dst: &mut Option<T>, src: &Option<T>) {
if dst.is_none() && src.is_some() {
dst.clone_from(src);
}
}
fn overwrite_if_present<T: Clone>(dst: &mut Option<T>, src: &Option<T>) {
if src.is_some() {
dst.clone_from(src);
}
}
pub(crate) fn merge_tls_info(dst: &mut Option<TlsInfo>, src: &Option<TlsInfo>) -> bool {
let Some(src_tls) = src else {
return false;
};
let Some(dst_tls) = dst else {
*dst = Some(src_tls.clone());
return true;
};
let mut updated = false;
let promote_sni = match (&dst_tls.sni, &src_tls.sni) {
(None, Some(_)) => true,
(Some(old), Some(new)) => is_partial_sni(old) && !is_partial_sni(new),
_ => false,
};
if promote_sni {
dst_tls.sni.clone_from(&src_tls.sni);
updated = true;
}
if dst_tls.version.is_none() && src_tls.version.is_some() {
dst_tls.version = src_tls.version;
updated = true;
}
if dst_tls.alpn.is_empty() && !src_tls.alpn.is_empty() {
dst_tls.alpn.clone_from(&src_tls.alpn);
updated = true;
}
if dst_tls.cipher_suite.is_none() && src_tls.cipher_suite.is_some() {
dst_tls.cipher_suite = src_tls.cipher_suite;
updated = true;
}
updated
}
fn merge_http_info(old_info: &mut HttpInfo, new_info: &HttpInfo) {
set_if_absent(&mut old_info.method, &new_info.method);
set_if_absent(&mut old_info.path, &new_info.path);
set_if_absent(&mut old_info.host, &new_info.host);
set_if_absent(&mut old_info.user_agent, &new_info.user_agent);
set_if_absent(&mut old_info.status_code, &new_info.status_code);
}
fn merge_quic_info(old_info: &mut QuicInfo, new_info: &QuicInfo) {
let old_priority = old_info.connection_state.priority();
let new_priority = new_info.connection_state.priority();
if new_priority > old_priority {
debug!(
"QUIC connection state progressed: {:?} -> {:?}",
old_info.connection_state, new_info.connection_state
);
old_info.connection_state = new_info.connection_state;
}
old_info.packet_type = new_info.packet_type;
if old_info.connection_id.is_empty() && !new_info.connection_id.is_empty() {
old_info.connection_id = new_info.connection_id.clone();
old_info.connection_id_hex = new_info.connection_id_hex.clone();
}
set_if_absent(&mut old_info.version_string, &new_info.version_string);
if let Some(new_reassembler) = &new_info.crypto_reassembler {
if old_info.crypto_reassembler.is_none() {
old_info.crypto_reassembler = Some(new_reassembler.clone());
} else if let Some(old_reassembler) = &mut old_info.crypto_reassembler
&& !old_reassembler.extraction_finished()
{
if new_reassembler.extraction_finished() {
old_reassembler.finish_extraction(new_reassembler.get_cached_tls_info().cloned());
} else {
for (offset, data) in new_reassembler.get_fragments() {
if let Err(e) = old_reassembler.add_fragment(offset, data.to_vec()) {
warn!("QUIC: Failed to merge CRYPTO fragment: {}", e);
}
}
let extracted = try_extract_tls_from_reassembler(old_reassembler, false)
.or_else(|| try_extract_tls_from_reassembler(old_reassembler, true));
merge_tls_info(&mut old_info.tls_info, &extracted);
}
}
if let Some(reassembler) = &old_info.crypto_reassembler {
merge_tls_info(
&mut old_info.tls_info,
&reassembler.get_cached_tls_info().cloned(),
);
}
}
if merge_tls_info(&mut old_info.tls_info, &new_info.tls_info) {
debug!("QUIC: Merged TLS info");
}
if new_info.has_crypto_frame {
old_info.has_crypto_frame = true;
}
if let Some(new_close) = &new_info.connection_close {
old_info.connection_close = Some(new_close.clone());
old_info.connection_state = match new_close.frame_type {
0x1c if new_close.error_code == 0 => {
debug!("QUIC: Connection entering draining state (NO_ERROR transport close)");
QuicConnectionState::Draining
}
0x1c => {
debug!(
"QUIC: Connection closed due to transport error: {}",
new_close.error_code
);
QuicConnectionState::Closed
}
0x1d => {
debug!(
"QUIC: Connection closed by application: {}",
new_close.error_code
);
QuicConnectionState::Closed
}
_ => {
debug!(
"QUIC: Connection closed (unknown frame type: 0x{:02x})",
new_close.frame_type
);
QuicConnectionState::Closed
}
};
debug!(
"QUIC: Updated connection state to {:?} due to CONNECTION_CLOSE frame",
old_info.connection_state
);
}
if matches!(
old_info.connection_state,
QuicConnectionState::Draining | QuicConnectionState::Closed
) && let Some(reassembler) = &mut old_info.crypto_reassembler
&& !reassembler.extraction_finished()
{
reassembler.finish_extraction(old_info.tls_info.clone());
}
overwrite_if_present(&mut old_info.idle_timeout, &new_info.idle_timeout);
}
fn merge_dns_info(old_info: &mut DnsInfo, new_info: &DnsInfo) {
set_if_absent(&mut old_info.query_name, &new_info.query_name);
set_if_absent(&mut old_info.query_type, &new_info.query_type);
for ip in &new_info.response_ips {
if old_info.response_ips.len() >= MAX_MERGED_RESPONSE_IPS {
break;
}
if !old_info.response_ips.contains(ip) {
old_info.response_ips.push(*ip);
}
}
if new_info.is_response {
old_info.is_response = true;
}
old_info.txid = new_info.txid;
overwrite_if_present(&mut old_info.rcode, &new_info.rcode);
overwrite_if_present(&mut old_info.nodata, &new_info.nodata);
}
fn merge_netbios_info(old_info: &mut NetBiosInfo, new_info: &NetBiosInfo) {
set_if_absent(&mut old_info.name, &new_info.name);
old_info.opcode = new_info.opcode;
old_info.transaction_id = new_info.transaction_id;
if new_info.is_response {
old_info.is_response = true;
}
overwrite_if_present(&mut old_info.response_status, &new_info.response_status);
}
fn merge_ssh_info(old_info: &mut SshInfo, new_info: &SshInfo) {
set_if_absent(&mut old_info.version, &new_info.version);
set_if_absent(&mut old_info.client_software, &new_info.client_software);
set_if_absent(&mut old_info.server_software, &new_info.server_software);
use crate::network::types::SshConnectionState;
match (&old_info.connection_state, &new_info.connection_state) {
(SshConnectionState::Banner, _)
| (
SshConnectionState::KeyExchange,
SshConnectionState::Authentication | SshConnectionState::Established,
)
| (SshConnectionState::Authentication, SshConnectionState::Established) => {
old_info.connection_state = new_info.connection_state.clone()
}
_ => {} }
match (&old_info.connection_state, &new_info.connection_state) {
(_, SshConnectionState::Established) if !new_info.algorithms.is_empty() => {
old_info.algorithms = new_info.algorithms.clone();
}
_ => {
for algo in &new_info.algorithms {
if !old_info.algorithms.contains(algo) {
old_info.algorithms.push(algo.clone());
}
}
}
}
set_if_absent(&mut old_info.auth_method, &new_info.auth_method);
}
fn merge_ftp_info(old_info: &mut FtpInfo, new_info: &FtpInfo) {
set_if_absent(&mut old_info.username, &new_info.username);
set_if_absent(&mut old_info.server_software, &new_info.server_software);
set_if_absent(&mut old_info.system_type, &new_info.system_type);
old_info.message_type = new_info.message_type;
overwrite_if_present(&mut old_info.command, &new_info.command);
overwrite_if_present(&mut old_info.args, &new_info.args);
overwrite_if_present(&mut old_info.response_code, &new_info.response_code);
overwrite_if_present(&mut old_info.response_message, &new_info.response_message);
}
fn merge_mqtt_info(old_info: &mut MqttInfo, new_info: &MqttInfo) {
set_if_absent(&mut old_info.version, &new_info.version);
set_if_absent(&mut old_info.client_id, &new_info.client_id);
set_if_absent(&mut old_info.topic, &new_info.topic);
set_if_absent(&mut old_info.qos, &new_info.qos);
old_info.packet_type = new_info.packet_type;
}
fn update_connection_rates(conn: &mut Connection) {
conn.update_rates();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::network::types::{AddrKind, Protocol, ProtocolState, TcpState, TlsVersion};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
#[test]
fn quic_merge_assembles_late_metadata_after_complete_sni() {
use crate::network::dpi::test_fixtures::{RFC9001_CLIENT_HELLO, from_hex};
let hello = from_hex(RFC9001_CLIENT_HELLO);
let split = hello
.windows(11)
.position(|bytes| bytes == b"example.com")
.unwrap()
+ 11;
let mut old = QuicInfo::new(1);
old.ensure_reassembler();
let reassembler = old.crypto_reassembler.as_mut().unwrap();
reassembler
.add_fragment(0, hello[..split].to_vec())
.unwrap();
old.tls_info = try_extract_tls_from_reassembler(reassembler, false);
assert_eq!(
old.tls_info.as_ref().unwrap().sni.as_deref(),
Some("example.com")
);
assert!(old.tls_info.as_ref().unwrap().alpn.is_empty());
let mut new = QuicInfo::new(1);
new.ensure_reassembler();
new.crypto_reassembler
.as_mut()
.unwrap()
.add_fragment(split as u64, hello[split..].to_vec())
.unwrap();
merge_quic_info(&mut old, &new);
assert_eq!(old.tls_info.as_ref().unwrap().alpn, vec!["alpn"]);
assert_eq!(
old.tls_info.as_ref().unwrap().version,
Some(TlsVersion::Tls13)
);
assert!(
old.crypto_reassembler
.as_ref()
.unwrap()
.get_fragments()
.next()
.is_none()
);
merge_quic_info(&mut old, &new);
assert!(
old.crypto_reassembler
.as_ref()
.unwrap()
.get_fragments()
.next()
.is_none()
);
}
#[test]
fn quic_merge_complete_packet_releases_old_partial_handshake() {
use crate::network::dpi::test_fixtures::{RFC9001_CLIENT_HELLO, from_hex};
let hello = from_hex(RFC9001_CLIENT_HELLO);
let mut old = QuicInfo::new(1);
old.ensure_reassembler();
old.crypto_reassembler
.as_mut()
.unwrap()
.add_fragment(0, hello[..20].to_vec())
.unwrap();
let mut new = QuicInfo::new(1);
new.ensure_reassembler();
let reassembler = new.crypto_reassembler.as_mut().unwrap();
reassembler.add_fragment(0, hello).unwrap();
new.tls_info = try_extract_tls_from_reassembler(reassembler, false);
merge_quic_info(&mut old, &new);
assert_eq!(old.tls_info.as_ref().unwrap().alpn, vec!["alpn"]);
assert!(
old.crypto_reassembler
.as_ref()
.unwrap()
.extraction_finished()
);
assert!(
old.crypto_reassembler
.as_ref()
.unwrap()
.get_fragments()
.next()
.is_none()
);
}
#[test]
fn quic_merge_close_releases_incomplete_handshake() {
let mut old = QuicInfo::new(1);
old.ensure_reassembler();
old.crypto_reassembler
.as_mut()
.unwrap()
.add_fragment(0, vec![1; 20])
.unwrap();
let mut closed = QuicInfo::new(1);
closed.connection_state = QuicConnectionState::Closed;
merge_quic_info(&mut old, &closed);
assert!(
old.crypto_reassembler
.as_ref()
.unwrap()
.extraction_finished()
);
assert!(
old.crypto_reassembler
.as_ref()
.unwrap()
.get_fragments()
.next()
.is_none()
);
}
fn create_test_connection() -> Connection {
Connection::new(
Protocol::Tcp,
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)), 12345),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 80),
ProtocolState::Tcp(TcpState::Established),
)
}
fn create_test_packet(is_outgoing: bool, fin: bool) -> ParsedPacket {
use crate::network::protocol::tcp::{TcpFlags, TcpHeaderInfo};
let mut packet = ParsedPacket::test_tcp(
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)), 12345),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 80),
TcpHeaderInfo {
seq: 1000,
ack: 2000,
window: 65535,
flags: TcpFlags {
syn: false,
ack: false,
fin,
rst: false,
},
payload_len: 60, window_scale: None,
},
);
packet.is_outgoing = is_outgoing;
packet.packet_len = 100;
packet
}
#[test]
fn test_merge_dns_response_ips_is_capped() {
let mut old = DnsInfo {
query_name: Some("example.com".to_string()),
query_type: None,
response_ips: Vec::new(),
is_response: true,
txid: 0x1234,
rcode: Some(0),
nodata: None,
};
for i in 0..(MAX_MERGED_RESPONSE_IPS as u32 * 4) {
let octets = i.to_be_bytes();
let new = DnsInfo {
query_name: None,
query_type: None,
response_ips: vec![IpAddr::V4(Ipv4Addr::new(
10, octets[1], octets[2], octets[3],
))],
is_response: true,
txid: 0x1234,
rcode: Some(0),
nodata: None,
};
merge_dns_info(&mut old, &new);
}
assert_eq!(old.response_ips.len(), MAX_MERGED_RESPONSE_IPS);
}
#[test]
fn test_merge_tls_info_promotes_partial_sni_per_field() {
let mut dst = Some(TlsInfo {
version: None,
sni: Some("exa[PARTIAL]".to_string()),
alpn: vec!["h3".to_string()],
cipher_suite: None,
});
let src = Some(TlsInfo {
version: Some(TlsVersion::Tls13),
sni: Some("example.com".to_string()),
alpn: Vec::new(),
cipher_suite: None,
});
assert!(merge_tls_info(&mut dst, &src));
let merged = dst.as_ref().unwrap();
assert_eq!(merged.sni.as_deref(), Some("example.com"));
assert_eq!(merged.alpn, vec!["h3".to_string()]);
assert_eq!(merged.version, Some(TlsVersion::Tls13));
let other = Some(TlsInfo {
version: None,
sni: Some("other.example".to_string()),
alpn: Vec::new(),
cipher_suite: None,
});
assert!(!merge_tls_info(&mut dst, &other));
assert_eq!(dst.unwrap().sni.as_deref(), Some("example.com"));
}
#[test]
fn test_merge_tls_info_fills_missing_sni() {
let mut dst = Some(TlsInfo {
version: Some(TlsVersion::Tls12),
sni: None,
alpn: Vec::new(),
cipher_suite: Some(0x1301),
});
let src = Some(TlsInfo {
version: Some(TlsVersion::Tls13),
sni: Some("example.com".to_string()),
alpn: Vec::new(),
cipher_suite: Some(0x1302),
});
assert!(merge_tls_info(&mut dst, &src));
let merged = dst.unwrap();
assert_eq!(merged.sni.as_deref(), Some("example.com"));
assert_eq!(merged.version, Some(TlsVersion::Tls12));
assert_eq!(merged.cipher_suite, Some(0x1301));
}
#[test]
fn test_merge_dns_keeps_rcode_and_tracks_latest_txid() {
let mut old = DnsInfo {
query_name: Some("example.com".to_string()),
query_type: None,
response_ips: Vec::new(),
is_response: true,
txid: 0x1111,
rcode: Some(3),
nodata: None,
};
let new_query = DnsInfo {
query_name: None,
query_type: None,
response_ips: Vec::new(),
is_response: false,
txid: 0x2222,
rcode: None,
nodata: None,
};
merge_dns_info(&mut old, &new_query);
assert_eq!(old.txid, 0x2222);
assert_eq!(old.rcode, Some(3), "a query must not erase the last rcode");
let new_response = DnsInfo {
query_name: None,
query_type: None,
response_ips: Vec::new(),
is_response: true,
txid: 0x2222,
rcode: Some(0),
nodata: None,
};
merge_dns_info(&mut old, &new_response);
assert_eq!(old.rcode, Some(0), "the latest response code wins");
}
#[test]
fn test_merge_netbios_keeps_status_and_tracks_latest_transaction() {
use crate::network::types::{NetBiosOpcode, NetBiosResponseStatus, NetBiosService};
let mut old = NetBiosInfo {
service: NetBiosService::NameService,
opcode: NetBiosOpcode::Response,
name: Some("FILESERVER".to_string()),
transaction_id: 0x1111,
is_response: true,
response_status: Some(NetBiosResponseStatus::NameService(3)),
};
let new_query = NetBiosInfo {
service: NetBiosService::NameService,
opcode: NetBiosOpcode::Query,
name: None,
transaction_id: 0x2222,
is_response: false,
response_status: None,
};
merge_netbios_info(&mut old, &new_query);
assert_eq!(old.opcode, NetBiosOpcode::Query);
assert_eq!(old.transaction_id, 0x2222);
assert_eq!(
old.response_status,
Some(NetBiosResponseStatus::NameService(3)),
"a request must not erase the last response status"
);
let new_response = NetBiosInfo {
service: NetBiosService::NameService,
opcode: NetBiosOpcode::Response,
name: None,
transaction_id: 0x2222,
is_response: true,
response_status: Some(NetBiosResponseStatus::NameService(0)),
};
merge_netbios_info(&mut old, &new_response);
assert_eq!(old.opcode, NetBiosOpcode::Response);
assert_eq!(
old.response_status,
Some(NetBiosResponseStatus::NameService(0))
);
}
#[test]
fn test_merge_packet_into_connection() {
let mut conn = create_test_connection();
let packet = create_test_packet(true, false);
let _tcp_events = merge_packet_into_connection(&mut conn, &packet, SystemTime::now());
assert_eq!(conn.packets_sent, 1);
assert_eq!(conn.bytes_sent, 100);
assert_eq!(conn.packets_received, 0);
}
#[test]
fn test_create_connection_from_packet() {
let packet = create_test_packet(false, false);
let conn = create_connection_from_packet(&packet, SystemTime::now());
assert_eq!(conn.packets_received, 1);
assert_eq!(conn.bytes_received, 100);
assert_eq!(conn.packets_sent, 0);
}
#[test]
fn vlan_observations_accumulate_without_duplicates_or_erasure() {
let mut packet = create_test_packet(true, false);
packet.vlan_id = Some(42);
let mut conn = create_connection_from_packet(&packet, SystemTime::now());
assert_eq!(conn.observed_vlan_ids, [42]);
packet.is_outgoing = false;
for vlan_id in [
None,
Some(42),
Some(100),
Some(0),
Some(42),
Some(65535),
None,
] {
packet.vlan_id = vlan_id;
merge_packet_into_connection(&mut conn, &packet, SystemTime::now());
}
assert_eq!(conn.observed_vlan_ids, [0, 42, 100]);
assert_eq!(conn.snapshot_clone().observed_vlan_ids, [0, 42, 100]);
let fresh = create_connection_from_packet(&packet, SystemTime::now());
assert!(fresh.observed_vlan_ids.is_empty());
}
#[test]
fn endpoint_kinds_are_copied_and_refreshed_on_merge() {
let mut packet = create_test_packet(false, false);
packet.local_addr_kind = AddrKind::Broadcast;
let conn = create_connection_from_packet(&packet, SystemTime::now());
assert_eq!(conn.local_addr_kind, AddrKind::Broadcast);
assert_eq!(conn.remote_addr_kind, AddrKind::Unicast);
let stale = create_test_packet(false, false);
let mut conn = create_connection_from_packet(&stale, SystemTime::now());
assert_eq!(conn.local_addr_kind, AddrKind::Unicast);
merge_packet_into_connection(&mut conn, &packet, SystemTime::now());
assert_eq!(conn.local_addr_kind, AddrKind::Broadcast);
}
#[test]
fn gateway_flag_is_copied_and_refreshed_on_merge() {
let mut packet = create_test_packet(false, false);
packet.remote_is_gateway = true;
let mut conn = create_connection_from_packet(&packet, SystemTime::now());
assert!(conn.remote_is_gateway);
packet.remote_is_gateway = false;
merge_packet_into_connection(&mut conn, &packet, SystemTime::now());
assert!(!conn.remote_is_gateway);
}
#[test]
fn test_new_connection_rate_tracker_initialization() {
let packet = create_test_packet(true, false);
let mut conn = create_connection_from_packet(&packet, SystemTime::now());
assert_eq!(conn.bytes_sent, 100);
assert_eq!(conn.bytes_received, 0);
let packet2 = create_test_packet(true, false);
let _tcp_events = merge_packet_into_connection(&mut conn, &packet2, SystemTime::now());
assert_eq!(conn.bytes_sent, 200);
assert_eq!(conn.bytes_received, 0);
conn.update_rates();
assert!(conn.current_outgoing_rate_bps >= 0.0);
}
#[test]
fn test_tcp_state_transitions() {
let flags = TcpFlags {
syn: true,
ack: false,
fin: false,
rst: false,
};
let new_state = update_tcp_state(TcpState::Unknown, &flags, true);
assert_eq!(new_state, TcpState::SynSent);
let flags = TcpFlags {
syn: true,
ack: true,
fin: false,
rst: false,
};
let new_state = update_tcp_state(TcpState::SynSent, &flags, false);
assert_eq!(new_state, TcpState::Established);
let flags = TcpFlags {
syn: false,
ack: false,
fin: true,
rst: false,
};
let new_state = update_tcp_state(TcpState::Established, &flags, true);
assert_eq!(new_state, TcpState::FinWait1);
let flags = TcpFlags {
syn: false,
ack: false,
fin: false,
rst: true,
};
let new_state = update_tcp_state(TcpState::Established, &flags, true);
assert_eq!(new_state, TcpState::Closed);
}
use crate::network::types::TcpAnalytics;
fn t0() -> SystemTime {
SystemTime::UNIX_EPOCH + Duration::from_secs(1_000)
}
fn send(analytics: &mut TcpAnalytics, seq: u32, len: u32) {
send_at(analytics, seq, len, t0());
}
fn base_segment() -> TcpSegment {
TcpSegment {
seq: 0,
ack: 0,
window: 65535,
payload_len: 0,
is_outgoing: false,
has_ack_flag: true,
is_syn: false,
is_rst: false,
window_scale: None,
}
}
fn send_at(analytics: &mut TcpAnalytics, seq: u32, len: u32, at: SystemTime) {
analyze_tcp_segment(
analytics,
TcpSegment {
seq,
payload_len: len,
is_outgoing: true,
has_ack_flag: false,
..base_segment()
},
at,
);
}
fn recv(analytics: &mut TcpAnalytics, seq: u32, ack: u32, len: u32) -> TcpMergeEvents {
recv_at(analytics, seq, ack, len, t0())
}
fn recv_at(
analytics: &mut TcpAnalytics,
seq: u32,
ack: u32,
len: u32,
at: SystemTime,
) -> TcpMergeEvents {
analyze_tcp_segment(
analytics,
TcpSegment {
seq,
ack,
payload_len: len,
..base_segment()
},
at,
)
}
fn window_segment(analytics: &mut TcpAnalytics, window: u16, is_outgoing: bool) {
analyze_tcp_segment(
analytics,
TcpSegment {
seq: 1,
ack: 1,
window,
is_outgoing,
..base_segment()
},
t0(),
);
}
fn window_recv_ack(analytics: &mut TcpAnalytics, ack: u32, window: u16) {
analyze_tcp_segment(
analytics,
TcpSegment {
ack,
window,
..base_segment()
},
t0(),
);
}
fn reset_recv(analytics: &mut TcpAnalytics) {
analyze_tcp_segment(
analytics,
TcpSegment {
seq: 1,
ack: 1,
window: 0,
is_rst: true,
..base_segment()
},
t0(),
);
}
fn window_send(analytics: &mut TcpAnalytics, window: u16) {
window_segment(analytics, window, true);
}
fn window_recv(analytics: &mut TcpAnalytics, window: u16) {
window_segment(analytics, window, false);
}
fn syn(analytics: &mut TcpAnalytics, is_outgoing: bool, window_scale: SynWindowScale) {
analyze_tcp_segment(
analytics,
TcpSegment {
payload_len: 1,
is_outgoing,
has_ack_flag: !is_outgoing,
is_syn: true,
window_scale: Some(window_scale),
..base_segment()
},
t0(),
);
}
#[test]
fn window_scale_applies_after_observed_handshake() {
let mut a = TcpAnalytics::new();
syn(&mut a, true, SynWindowScale::Present(7));
let out = a.last_window_out.unwrap();
assert_eq!(out.shift, 0, "SYN windows are never scaled");
assert!(out.scale_known, "a SYN window is an exact byte count");
syn(&mut a, false, SynWindowScale::Present(8));
assert_eq!(
a.last_window_in.unwrap().shift,
0,
"SYN-ACK windows are never scaled"
);
recv(&mut a, 1, 1, 100);
let inbound = a.last_window_in.unwrap();
assert_eq!(inbound.shift, 8, "inbound uses the remote's shift");
assert_eq!(inbound.bytes(), 65535 << 8);
send(&mut a, 1, 100);
let outbound = a.last_window_out.unwrap();
assert_eq!(outbound.shift, 7, "outbound uses the local shift");
assert_eq!(outbound.bytes(), 65535 << 7);
}
fn syn_packet(is_outgoing: bool, is_syn_ack: bool, shift: u8) -> ParsedPacket {
use crate::network::protocol::tcp::{TcpFlags, TcpHeaderInfo};
let mut packet = ParsedPacket::test_tcp(
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)), 12345),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 80),
TcpHeaderInfo {
seq: 0,
ack: 0,
window: 65535,
flags: TcpFlags {
syn: true,
ack: is_syn_ack,
fin: false,
rst: false,
},
payload_len: 0,
window_scale: Some(SynWindowScale::Present(shift)),
},
);
packet.is_outgoing = is_outgoing;
packet.packet_len = 74;
packet
}
#[test]
fn the_connections_first_packet_reaches_the_analytics() {
let now = t0();
let mut conn = create_connection_from_packet(&syn_packet(true, false, 7), now);
merge_packet_into_connection(&mut conn, &syn_packet(false, true, 8), now);
merge_packet_into_connection(&mut conn, &create_test_packet(false, false), now);
let analytics = conn.tcp_analytics.unwrap();
assert_eq!(analytics.window_scale_out, Some(7));
assert_eq!(analytics.window_scale_in, Some(8));
assert!(analytics.window_scale_known());
assert_eq!(analytics.last_window_in.unwrap().bytes(), 65535 << 8);
}
#[test]
fn window_directions_are_tracked_separately() {
let mut a = TcpAnalytics::new();
syn(&mut a, true, SynWindowScale::Present(7));
syn(&mut a, false, SynWindowScale::Present(7));
window_recv(&mut a, 8);
window_send(&mut a, 1100);
assert_eq!(a.last_window_in.unwrap().bytes(), 8 << 7);
assert_eq!(a.last_window_out.unwrap().bytes(), 1100 << 7);
}
#[test]
fn window_scale_off_when_one_side_lacks_the_option() {
let mut a = TcpAnalytics::new();
syn(&mut a, true, SynWindowScale::Present(7));
syn(&mut a, false, SynWindowScale::Absent); recv(&mut a, 1, 1, 100);
let inbound = a.last_window_in.unwrap();
assert_eq!(inbound.shift, 0);
assert!(inbound.scale_known, "absence of the option is a conclusion");
assert_eq!(inbound.bytes(), 65535);
}
#[test]
fn truncated_syn_options_do_not_disable_scaling() {
let mut a = TcpAnalytics::new();
syn(&mut a, true, SynWindowScale::Present(7));
syn(&mut a, false, SynWindowScale::Unknown); recv(&mut a, 1, 1, 100);
let inbound = a.last_window_in.unwrap();
assert_eq!(inbound.shift, 0, "no conclusion yet, raw window");
assert!(!inbound.scale_known);
syn(&mut a, false, SynWindowScale::Present(8)); recv(&mut a, 101, 1, 100);
let inbound = a.last_window_in.unwrap();
assert_eq!(inbound.shift, 8);
assert!(inbound.scale_known);
assert_eq!(inbound.bytes(), 65535 << 8);
}
#[test]
fn window_unscaled_when_handshake_not_observed() {
let mut a = TcpAnalytics::new();
recv(&mut a, 1, 1, 100);
let inbound = a.last_window_in.unwrap();
assert_eq!(inbound.shift, 0);
assert!(!inbound.scale_known);
assert_eq!(inbound.raw, 65535);
}
#[test]
fn detects_retransmit_after_a_sequence_gap() {
let mut a = TcpAnalytics::new();
send(&mut a, 0, 100); assert!(a.seen_outbound);
send(&mut a, 5000, 100); assert_eq!(a.retransmit_count, 0, "a gap is not a retransmission");
assert_eq!(a.highest_seq_outbound, 5100, "tracker must resync on a gap");
send(&mut a, 5000, 100); assert_eq!(a.retransmit_count, 1);
send(&mut a, 5100, 100); assert_eq!(a.retransmit_count, 1);
assert_eq!(a.highest_seq_outbound, 5200);
}
#[test]
fn sequence_comparison_survives_wraparound() {
let mut a = TcpAnalytics::new();
send(&mut a, u32::MAX - 50, 100); assert_eq!(a.highest_seq_outbound, 49);
send(&mut a, 49, 100); assert_eq!(a.retransmit_count, 0);
send(&mut a, u32::MAX - 50, 100); assert_eq!(a.retransmit_count, 1);
}
#[test]
fn inbound_data_segments_are_not_duplicate_acks() {
let mut a = TcpAnalytics::new();
let mut seq = 1000;
for _ in 0..20 {
recv(&mut a, seq, 500, 1400);
seq += 1400;
}
assert_eq!(a.duplicate_ack_count, 0);
assert_eq!(a.fast_retransmit_count, 0);
assert_eq!(a.out_of_order_count, 0);
}
#[test]
fn fast_retransmit_fires_once_per_dup_ack_run() {
let mut a = TcpAnalytics::new();
send(&mut a, 1000, 500);
recv(&mut a, 0, 500, 0); recv(&mut a, 0, 500, 0); recv(&mut a, 0, 500, 0); assert_eq!(a.fast_retransmit_count, 0);
recv(&mut a, 0, 500, 0); assert_eq!(a.fast_retransmit_count, 1);
recv(&mut a, 0, 500, 0); assert_eq!(a.fast_retransmit_count, 1);
assert_eq!(a.duplicate_ack_count, 4, "cumulative, not the run length");
recv(&mut a, 0, 900, 0);
assert_eq!(a.dup_ack_run, 0);
for _ in 0..3 {
recv(&mut a, 0, 900, 0);
}
assert_eq!(a.fast_retransmit_count, 2);
assert_eq!(a.duplicate_ack_count, 7);
}
#[test]
fn keepalives_without_outstanding_data_are_not_duplicate_acks() {
let mut a = TcpAnalytics::new();
for _ in 0..13 {
recv(&mut a, 0, 500, 0);
}
assert_eq!(a.duplicate_ack_count, 0);
assert_eq!(a.fast_retransmit_count, 0);
}
#[test]
fn acks_covering_everything_sent_are_not_duplicate_acks() {
let mut a = TcpAnalytics::new();
send(&mut a, 1000, 500);
for _ in 0..5 {
recv(&mut a, 0, 1500, 0);
}
assert_eq!(a.duplicate_ack_count, 0);
assert_eq!(a.fast_retransmit_count, 0);
}
#[test]
fn window_updates_are_not_duplicate_acks() {
let mut a = TcpAnalytics::new();
send(&mut a, 1000, 500);
recv(&mut a, 0, 1200, 0);
window_recv_ack(&mut a, 1200, 32768);
window_recv_ack(&mut a, 1200, 16384);
assert_eq!(a.duplicate_ack_count, 0);
window_recv_ack(&mut a, 1200, 16384);
assert_eq!(a.duplicate_ack_count, 1);
}
#[test]
fn reset_does_not_overwrite_the_last_advertised_window() {
let mut a = TcpAnalytics::new();
window_recv(&mut a, 501);
reset_recv(&mut a);
assert_eq!(a.last_window_in.unwrap().raw, 501);
}
#[test]
fn covering_ack_completes_an_rtt_probe() {
let mut a = TcpAnalytics::new();
send_at(&mut a, 0, 100, t0()); let events = recv_at(&mut a, 0, 100, 0, t0() + Duration::from_millis(40));
assert_eq!(events.rtt_sample, Some(Duration::from_millis(40)));
assert_eq!(a.smoothed_rtt, Some(Duration::from_millis(40)));
assert_eq!(a.rtt_probe, None, "a completed probe must not re-fire");
}
#[test]
fn partial_ack_does_not_complete_the_probe() {
let mut a = TcpAnalytics::new();
send_at(&mut a, 0, 100, t0());
let events = recv_at(&mut a, 0, 50, 0, t0() + Duration::from_millis(40));
assert_eq!(events.rtt_sample, None, "50 acks only half the timed bytes");
assert!(a.rtt_probe.is_some(), "the probe stays armed");
let events = recv_at(&mut a, 0, 100, 0, t0() + Duration::from_millis(80));
assert_eq!(events.rtt_sample, Some(Duration::from_millis(80)));
}
#[test]
fn retransmission_invalidates_the_probe() {
let mut a = TcpAnalytics::new();
send_at(&mut a, 0, 100, t0());
send_at(&mut a, 0, 100, t0() + Duration::from_millis(10)); assert_eq!(a.retransmit_count, 1);
let events = recv_at(&mut a, 0, 100, 0, t0() + Duration::from_millis(50));
assert_eq!(events.rtt_sample, None);
}
#[test]
fn smoothed_rtt_is_an_ewma_of_samples() {
let mut a = TcpAnalytics::new();
send_at(&mut a, 0, 100, t0());
recv_at(&mut a, 0, 100, 0, t0() + Duration::from_millis(80));
assert_eq!(a.smoothed_rtt, Some(Duration::from_millis(80)));
let sent = t0() + Duration::from_millis(100);
send_at(&mut a, 100, 100, sent);
recv_at(&mut a, 0, 200, 0, sent + Duration::from_millis(16));
assert_eq!(a.smoothed_rtt, Some(Duration::from_millis(72)));
}
#[test]
fn a_young_probe_is_not_replaced_but_a_stale_one_is() {
let mut a = TcpAnalytics::new();
send_at(&mut a, 0, 100, t0());
send_at(&mut a, 100, 100, t0() + Duration::from_millis(5));
assert_eq!(
a.rtt_probe.map(|(seq, _)| seq),
Some(100),
"the oldest outstanding segment stays the timed one"
);
let late = t0() + RTT_PROBE_TIMEOUT + Duration::from_secs(1);
send_at(&mut a, 200, 100, late);
assert_eq!(a.rtt_probe, Some((300, late)));
}
#[test]
fn probe_completion_survives_sequence_wraparound() {
let mut a = TcpAnalytics::new();
send_at(&mut a, u32::MAX - 50, 100, t0()); let events = recv_at(&mut a, 0, 49, 0, t0() + Duration::from_millis(30));
assert_eq!(events.rtt_sample, Some(Duration::from_millis(30)));
}
#[test]
fn inbound_data_segments_can_complete_the_probe() {
let mut a = TcpAnalytics::new();
send_at(&mut a, 0, 100, t0());
let events = recv_at(&mut a, 0, 100, 1400, t0() + Duration::from_millis(25));
assert_eq!(events.rtt_sample, Some(Duration::from_millis(25)));
}
}