98 lines
3.1 KiB
Java
98 lines
3.1 KiB
Java
package com.gigazelensky.antispoof.data;
|
|
|
|
import java.util.ArrayDeque;
|
|
import java.util.ArrayList;
|
|
import java.util.Deque;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* Per-player sliding window tracking TCP handshake RTT vs in-game KeepAlive/Ping RTT for proxy/VPN heuristics.
|
|
*/
|
|
public final class ProxyState {
|
|
private static final int MAX_HISTORY = 32;
|
|
|
|
private final Deque<Long> recentDiffs = new ArrayDeque<>();
|
|
private final Deque<Long> recentPings = new ArrayDeque<>();
|
|
private final Deque<Long> recentHandshakeRtts = new ArrayDeque<>();
|
|
|
|
private long handshakeRttMs;
|
|
private long lastPingMs;
|
|
private String lastPingSource;
|
|
private long lastDiffMs;
|
|
private long lastSampleAt;
|
|
|
|
public synchronized void recordHandshakeRtt(long rttMs) {
|
|
if (rttMs <= 0L) {
|
|
return;
|
|
}
|
|
this.handshakeRttMs = rttMs;
|
|
recentHandshakeRtts.addLast(rttMs);
|
|
while (recentHandshakeRtts.size() > MAX_HISTORY) {
|
|
recentHandshakeRtts.removeFirst();
|
|
}
|
|
}
|
|
|
|
public synchronized void recordPingSample(long pingMs, String source) {
|
|
if (pingMs < 0L) {
|
|
return;
|
|
}
|
|
this.lastPingMs = pingMs;
|
|
this.lastPingSource = source;
|
|
this.lastSampleAt = System.currentTimeMillis();
|
|
recentPings.addLast(pingMs);
|
|
while (recentPings.size() > MAX_HISTORY) {
|
|
recentPings.removeFirst();
|
|
}
|
|
if (handshakeRttMs > 0L) {
|
|
long diff = Math.abs(pingMs - handshakeRttMs);
|
|
this.lastDiffMs = diff;
|
|
recentDiffs.addLast(diff);
|
|
while (recentDiffs.size() > MAX_HISTORY) {
|
|
recentDiffs.removeFirst();
|
|
}
|
|
}
|
|
}
|
|
|
|
public synchronized ProxyMetrics snapshot(int windowSize) {
|
|
int limit = windowSize > 0 ? Math.min(windowSize, recentDiffs.size()) : recentDiffs.size();
|
|
List<Long> diffs = tail(recentDiffs, limit);
|
|
List<Long> pings = tail(recentPings, windowSize > 0 ? windowSize : recentPings.size());
|
|
List<Long> handshakes = tail(recentHandshakeRtts, windowSize > 0 ? windowSize : recentHandshakeRtts.size());
|
|
|
|
long sum = 0L;
|
|
long min = diffs.isEmpty() ? 0L : Long.MAX_VALUE;
|
|
long max = diffs.isEmpty() ? 0L : Long.MIN_VALUE;
|
|
for (long d : diffs) {
|
|
sum += d;
|
|
if (d < min) min = d;
|
|
if (d > max) max = d;
|
|
}
|
|
double avg = diffs.isEmpty() ? 0.0 : (double) sum / diffs.size();
|
|
return new ProxyMetrics(
|
|
handshakeRttMs,
|
|
lastPingMs,
|
|
lastPingSource,
|
|
lastDiffMs,
|
|
avg,
|
|
min,
|
|
max,
|
|
diffs.size(),
|
|
lastSampleAt,
|
|
diffs,
|
|
pings,
|
|
handshakes
|
|
);
|
|
}
|
|
|
|
private static List<Long> tail(Deque<Long> deque, int max) {
|
|
if (deque.isEmpty() || max <= 0) {
|
|
return List.of();
|
|
}
|
|
List<Long> all = new ArrayList<>(deque);
|
|
if (all.size() <= max) {
|
|
return List.copyOf(all);
|
|
}
|
|
return List.copyOf(all.subList(all.size() - max, all.size()));
|
|
}
|
|
}
|