From e2a7223dbb9e9d5c32d45dd697094f249a3bbd14 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Wed, 18 Nov 2026 23:13:32 +0000
Subject: [PATCH 01/15] Expose a platform-neutral vote receiver adapter
---
.../votifier/net/PlatformVoteReceiver.java | 186 ++++++++++++++++++
.../tests/PlatformVoteReceiverTest.java | 99 ++++++++++
2 files changed, 285 insertions(+)
create mode 100644 VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
create mode 100644 VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
new file mode 100644
index 0000000..4e2ac0b
--- /dev/null
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
@@ -0,0 +1,186 @@
+package com.vexsoftware.votifier.net;
+
+import java.io.IOException;
+import java.security.Key;
+import java.security.KeyPair;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import com.vexsoftware.votifier.ForwardServer;
+import com.vexsoftware.votifier.model.Vote;
+
+/** Platform-neutral adapter for the shared listener and forwarding runtime. */
+public final class PlatformVoteReceiver extends VoteReceiver {
+
+ /**
+ * Binds a receiver using explicit per-listener settings. Start it with
+ * {@link VoteReceiver#start()} and retire it with {@link VoteReceiver#shutdown()}.
+ *
+ *
The callback is invoked on a connection worker before forwarding and may
+ * run concurrently for different votes. It should enqueue platform work on
+ * the appropriate scheduler and return promptly. Treat the vote as read-only
+ * because forwarding uses the same object. The adapter owns the lifecycle of
+ * work it enqueues on its scheduler.
+ *
+ * @param settings listener configuration and protocol policy
+ * @param logger logger for the receiver
+ * @param onVote callback for a parsed, accepted vote
+ * @return bound, unstarted receiver
+ * @throws Exception if the listener cannot bind
+ */
+ public static PlatformVoteReceiver bind(Settings settings, Logger logger, Consumer onVote) throws Exception {
+ return new PlatformVoteReceiver(Objects.requireNonNull(settings), Objects.requireNonNull(logger),
+ Objects.requireNonNull(onVote));
+ }
+
+ /**
+ * Configuration for one listener. Supply a new configuration and receiver
+ * when changing policy. Token support controls the greeting, while disableV1
+ * requires V2 authentication. An empty trusted-proxy set trusts no peer.
+ */
+ public record Settings(String host, int port, String version, boolean tokenSupport, boolean disableV1,
+ KeyPair keyPair, Map tokens, Set trustedProxyIps, ThrottleConfig throttle,
+ Map forwarding) {
+ public Settings {
+ Objects.requireNonNull(version);
+ if (!disableV1) {
+ Objects.requireNonNull(keyPair, "Legacy V1 requires an RSA key pair");
+ }
+ tokens = Map.copyOf(tokens);
+ trustedProxyIps = Set.copyOf(trustedProxyIps);
+ Map targets = new LinkedHashMap<>();
+ forwarding.forEach((name, target) -> targets.put(Objects.requireNonNull(name), copyTarget(target)));
+ forwarding = Collections.unmodifiableMap(targets);
+ }
+
+ @Override
+ public Map forwarding() {
+ Map targets = new LinkedHashMap<>();
+ forwarding.forEach((name, target) -> targets.put(name, copyTarget(target)));
+ return Collections.unmodifiableMap(targets);
+ }
+
+ @Override
+ public String toString() {
+ return "PlatformVoteReceiver.Settings";
+ }
+ }
+
+ private static ForwardServer copyTarget(ForwardServer target) {
+ return new ForwardServer(target.isEnabled(), target.getHost(), target.getPort(), target.getKey(),
+ target.getToken());
+ }
+
+ private final Settings settings;
+ private final Logger logger;
+ private final Consumer onVote;
+
+ private PlatformVoteReceiver(Settings settings, Logger logger, Consumer onVote) throws Exception {
+ super(settings.host(), settings.port());
+ this.settings = settings;
+ this.logger = logger;
+ this.onVote = onVote;
+ }
+
+ @Override
+ public boolean isUseTokens() {
+ return settings.tokenSupport();
+ }
+
+ @Override
+ public boolean isDisableV1() {
+ return settings.disableV1();
+ }
+
+ @Override
+ public ThrottleConfig getThrottleConfig() {
+ return settings.throttle();
+ }
+
+ @Override
+ public Set getTrustedProxyIps() {
+ return settings.trustedProxyIps();
+ }
+
+ @Override
+ public void logWarning(String warning) {
+ logger.warning(warning);
+ }
+
+ @Override
+ public void logSevere(String message) {
+ // The superclass can report bind failures before the adapter is initialized.
+ Logger sink = logger == null ? Logger.getLogger(PlatformVoteReceiver.class.getName()) : logger;
+ sink.severe(message);
+ }
+
+ @Override
+ public void log(String message) {
+ logger.info(message);
+ }
+
+ @Override
+ public void debug(String message) {
+ if (logger != null) {
+ logger.fine(message);
+ }
+ }
+
+ @Override
+ public void debug(Exception exception) {
+ logger.log(Level.FINE, "Vote receiver operation failed: {0}", VoteLogSafety.exceptionType(exception));
+ }
+
+ @Override
+ public String getVersion() {
+ return settings.version();
+ }
+
+ @Override
+ public Set getServers() {
+ return settings.forwarding.keySet();
+ }
+
+ @Override
+ public KeyPair getKeyPair() {
+ return settings.keyPair();
+ }
+
+ @Override
+ public Map getTokens() {
+ return settings.tokens();
+ }
+
+ @Override
+ public ForwardServer getServerData(String name) {
+ ForwardServer target = settings.forwarding.get(name);
+ return target == null ? null : copyTarget(target);
+ }
+
+ @Override
+ public void callEvent(Vote vote) {
+ onVote.accept(vote);
+ }
+
+ @Override
+ public void initialize() throws Exception {
+ try {
+ super.initialize();
+ } catch (Exception failure) {
+ if (getServer() != null) {
+ try {
+ getServer().close();
+ } catch (IOException closeFailure) {
+ failure.addSuppressed(closeFailure);
+ }
+ }
+ throw failure;
+ }
+ }
+}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
new file mode 100644
index 0000000..c54520c
--- /dev/null
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
@@ -0,0 +1,99 @@
+package com.bencodez.votifierplus.tests;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.security.Key;
+import java.util.Base64;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Logger;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.Mac;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.gson.JsonObject;
+import com.vexsoftware.votifier.ForwardServer;
+import com.vexsoftware.votifier.model.Vote;
+import com.vexsoftware.votifier.net.PlatformVoteReceiver;
+import com.vexsoftware.votifier.net.VoteReceiver;
+
+public class PlatformVoteReceiverTest {
+
+ @Test
+ public void boundReceiverDeliversOneAuthenticatedVoteAndReleasesListener() throws Exception {
+ Key dummyTokenKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ var accepted = new LinkedBlockingQueue();
+ var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", false, true,
+ null, Map.of("example.test", dummyTokenKey), Set.of(), null, Map.of());
+ VoteReceiver bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), accepted::add);
+ int port = bound.getServer().getLocalPort();
+ try {
+ bound.start();
+ try (Socket client = new Socket("127.0.0.1", port)) {
+ client.setSoTimeout(5000);
+ var reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
+ String greeting = reader.readLine();
+ assertTrue(greeting.startsWith("VOTIFIER 2 "));
+ JsonObject inner = new JsonObject();
+ inner.addProperty("serviceName", "example.test");
+ inner.addProperty("username", "TestVoter");
+ inner.addProperty("address", "127.0.0.1");
+ inner.addProperty("timestamp", "TestTimestamp");
+ inner.addProperty("challenge", greeting.substring("VOTIFIER 2 ".length()));
+ String payload = inner.toString();
+
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(dummyTokenKey);
+ JsonObject envelope = new JsonObject();
+ envelope.addProperty("payload", payload);
+ envelope.addProperty("signature", Base64.getEncoder()
+ .encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))));
+ client.getOutputStream().write((envelope + "\n").getBytes(StandardCharsets.UTF_8));
+ assertTrue(reader.readLine().contains("\"status\":\"ok\""));
+ }
+ Vote vote = accepted.poll(5, TimeUnit.SECONDS);
+ assertNotNull(vote);
+ assertEquals("TestVoter", vote.getUsername());
+ assertEquals("127.0.0.1", vote.getSourceAddress());
+ } finally {
+ bound.shutdown();
+ bound.join(5000);
+ }
+ assertFalse(bound.isAlive());
+ assertNull(accepted.poll());
+ try (ServerSocket rebound = new ServerSocket()) {
+ rebound.bind(new InetSocketAddress("127.0.0.1", port));
+ }
+ }
+
+ @Test
+ public void boundReceiverSnapshotsForwardingAuthentication() throws Exception {
+ Key dummyTokenKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ var target = new ForwardServer(true, "127.0.0.1", 1234, "", dummyTokenKey);
+ var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
+ null, Map.of(), Set.of(), null, Map.of("test", target));
+ target.setToken(null);
+ settings.forwarding().get("test").setToken(null);
+ VoteReceiver bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {});
+ try {
+ bound.getServerData("test").setToken(null);
+ assertTrue(bound.getServerData("test").isUseTokens());
+ } finally {
+ bound.shutdown();
+ }
+ }
+}
From 687c7d3dfcbf3a0d69949d75c4c903ed771624b9 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Wed, 18 Nov 2026 23:16:12 +0000
Subject: [PATCH 02/15] Guard the platform receiver lifecycle and callback
boundary
---
.../votifier/net/PlatformVoteReceiver.java | 16 +++++++--
.../tests/PlatformVoteReceiverTest.java | 33 +++++++++++++++++++
2 files changed, 47 insertions(+), 2 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
index 4e2ac0b..d7fa284 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
@@ -26,7 +26,12 @@ public final class PlatformVoteReceiver extends VoteReceiver {
* run concurrently for different votes. It should enqueue platform work on
* the appropriate scheduler and return promptly. Treat the vote as read-only
* because forwarding uses the same object. The adapter owns the lifecycle of
- * work it enqueues on its scheduler.
+ * work it enqueues on its scheduler. The receiver can invoke the callback
+ * for connections already admitted while shutdown drains the worker pool.
+ * The adapter must gate and drain its scheduler work during disable.
+ *
+ * The wire response acknowledges protocol acceptance before this
+ * callback. Callback failures are logged and forwarding can still proceed.
*
* @param settings listener configuration and protocol policy
* @param logger logger for the receiver
@@ -165,11 +170,18 @@ public ForwardServer getServerData(String name) {
@Override
public void callEvent(Vote vote) {
- onVote.accept(vote);
+ try {
+ onVote.accept(vote);
+ } catch (RuntimeException failure) {
+ logger.warning("Vote callback failed: " + VoteLogSafety.exceptionType(failure));
+ }
}
@Override
public void initialize() throws Exception {
+ if (getServer() != null) {
+ throw new IllegalStateException("Bind a new receiver to replace this listener");
+ }
try {
super.initialize();
} catch (Exception failure) {
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
index c54520c..6b5bad2 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
@@ -2,6 +2,9 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -96,4 +99,34 @@ public void boundReceiverSnapshotsForwardingAuthentication() throws Exception {
bound.shutdown();
}
}
+
+ @Test
+ public void repeatInitializationPreservesTheBoundSocket() throws Exception {
+ var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
+ null, Map.of(), Set.of(), null, Map.of());
+ var bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {});
+ try {
+ ServerSocket original = bound.getServer();
+ assertThrows(IllegalStateException.class, bound::initialize);
+ assertSame(original, bound.getServer());
+ assertFalse(original.isClosed());
+ } finally {
+ bound.shutdown();
+ }
+ assertThrows(IllegalStateException.class, bound::initialize);
+ }
+
+ @Test
+ public void callbackRejectionDoesNotEscapeToTheReceiverForwardingPath() throws Exception {
+ var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
+ null, Map.of(), Set.of(), null, Map.of());
+ var bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {
+ throw new java.util.concurrent.RejectedExecutionException();
+ });
+ try {
+ assertDoesNotThrow(() -> bound.callEvent(new Vote()));
+ } finally {
+ bound.shutdown();
+ }
+ }
}
From f2b105afbb8db9545e97f93035214288e7c4500f Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Wed, 18 Nov 2026 23:37:15 +0000
Subject: [PATCH 03/15] Close retiring vote sockets and bound forwarding work
---
.../votifier/net/VoteConnectionHandler.java | 6 +-
.../votifier/net/VoteForwarder.java | 81 ++++++-
.../votifier/net/VoteReceiver.java | 225 +++++++++++-------
.../tests/VoteReceiverLifecycleTest.java | 128 +++++++++-
.../tests/net/VoteForwarderHandshakeTest.java | 58 +++++
5 files changed, 398 insertions(+), 100 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteConnectionHandler.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteConnectionHandler.java
index ba9d49c..86ea0a5 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteConnectionHandler.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteConnectionHandler.java
@@ -155,8 +155,10 @@ public Vote handle(Socket socket) {
throttleService.logWarning(receiver, "timeout|" + remoteIp,
"Connection timeout while waiting for vote payload from " + remoteIp);
} catch (SocketException ex) {
- throttleService.logWarning(receiver, "socket|" + remoteIp,
- "Connection error: Protocol error from " + remoteIp);
+ if (!receiver.isStopping()) {
+ throttleService.logWarning(receiver, "socket|" + remoteIp,
+ "Connection error: Protocol error from " + remoteIp);
+ }
} catch (Exception ex) {
throttleService.logWarning(receiver, "generic|" + remoteIp, "Error processing vote from " + remoteIp + ": "
+ VoteLogSafety.exceptionType(ex));
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index faa1a6c..64dcc4a 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -1,12 +1,19 @@
package com.vexsoftware.votifier.net;
import java.io.BufferedReader;
+import java.io.FilterInputStream;
+import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
+import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
@@ -27,8 +34,12 @@ public class VoteForwarder {
private static final String FIELD_TIMESTAMP = "timestamp";
private static final String FIELD_CHALLENGE = "challenge";
private static final int MAX_HANDSHAKE_CHARS = 512;
+ private static final int CONNECT_TIMEOUT_MILLIS = 1000;
+ private static final int HANDSHAKE_TIMEOUT_MILLIS = 3000;
private final VoteReceiver receiver;
+ private final Set activeSockets = new HashSet<>();
+ private volatile boolean stopped;
public VoteForwarder(VoteReceiver receiver) {
this.receiver = receiver;
@@ -36,6 +47,9 @@ public VoteForwarder(VoteReceiver receiver) {
public void forwardVote(Vote vote) {
for (String name : receiver.getServers()) {
+ if (stopped || Thread.currentThread().isInterrupted()) {
+ return;
+ }
ForwardServer server = receiver.getServerData(name);
if (!server.isEnabled()) {
@@ -45,15 +59,17 @@ public void forwardVote(Vote vote) {
receiver.debug("Preparing to forward vote to: " + VoteLogSafety.field(name) + ", tokens mode: " + server.isUseTokens());
- try (Socket socket = new Socket()) {
- socket.connect(new InetSocketAddress(server.getHost(), server.getPort()), 1000);
- socket.setSoTimeout(3000);
-
- BufferedReader in = new BufferedReader(
- new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
+ Socket socket = new Socket();
+ try (socket) {
+ synchronized (activeSockets) {
+ if (stopped) {
+ return;
+ }
+ activeSockets.add(socket);
+ }
+ socket.connect(new InetSocketAddress(server.getHost(), server.getPort()), CONNECT_TIMEOUT_MILLIS);
+ String greeting = readHandshakeLine(socket, HANDSHAKE_TIMEOUT_MILLIS);
OutputStream out = socket.getOutputStream();
-
- String greeting = readHandshakeLine(in);
receiver.debug("Received handshake from " + VoteLogSafety.field(name)
+ " (" + (greeting == null ? 0 : greeting.length()) + " chars)");
@@ -95,10 +111,55 @@ public void forwardVote(Vote vote) {
out.flush();
receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)");
} catch (Exception ex) {
- receiver.log("Failed to forward vote to " + VoteLogSafety.field(name) + ": "
- + VoteLogSafety.exceptionType(ex));
+ if (!stopped) {
+ receiver.log("Failed to forward vote to " + VoteLogSafety.field(name) + ": "
+ + VoteLogSafety.exceptionType(ex));
+ }
+ } finally {
+ synchronized (activeSockets) {
+ activeSockets.remove(socket);
+ }
+ }
+ }
+ }
+
+ void stop() {
+ List sockets;
+ synchronized (activeSockets) {
+ stopped = true;
+ sockets = List.copyOf(activeSockets);
+ activeSockets.clear();
+ }
+ for (Socket socket : sockets) {
+ try {
+ socket.close();
+ } catch (IOException ex) {
+ receiver.debug("Failed to close forwarding socket: " + VoteLogSafety.exceptionType(ex));
+ }
+ }
+ }
+
+ static String readHandshakeLine(Socket socket, int timeoutMillis) throws Exception {
+ long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+ // The decoder can make multiple reads to produce one character. Apply the
+ // remaining budget at each socket read, including CR lookahead.
+ var input = new FilterInputStream(socket.getInputStream()) {
+ @Override
+ public int read(byte[] bytes, int offset, int length) throws IOException {
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ throw new SocketTimeoutException("Forward handshake timed out");
+ }
+ socket.setSoTimeout((int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining)));
+ return super.read(bytes, offset, length);
}
+ };
+ var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
+ String greeting = readHandshakeLine(reader);
+ if (deadline - System.nanoTime() <= 0) {
+ throw new SocketTimeoutException("Forward handshake timed out");
}
+ return greeting;
}
static String readHandshakeLine(BufferedReader in) throws Exception {
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index c9cf52b..7c2d8be 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -72,6 +72,8 @@
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
@@ -97,6 +99,8 @@ public abstract class VoteReceiver extends Thread {
private ServerSocket server;
private volatile boolean running = true;
+ private final Object lifecycleLock = new Object();
+ private final Set connections = new HashSet<>();
@Getter
private volatile VoteThrottleService throttleService;
@@ -128,37 +132,64 @@ public void initialize() throws Exception {
}
}
+ /**
+ * Closes the listener and all admitted sockets, then waits for workers within
+ * bounded drain windows. Platform-owned callbacks must return promptly.
+ */
public void shutdown() {
- running = false;
-
+ List sockets;
+ synchronized (lifecycleLock) {
+ running = false;
+ sockets = List.copyOf(connections);
+ connections.clear();
+ }
if (server != null) {
try {
server.close();
- } catch (Exception ex) {
+ } catch (IOException ex) {
debug(ex);
}
}
+ sockets.forEach(this::closeConnection);
+ try {
+ shutdownExecutor(connectionExecutor, "connection", () -> {});
+ } finally {
+ shutdownExecutor(forwardExecutor, "forward", () -> voteForwarder.stop());
+ }
+ }
- shutdownExecutor(connectionExecutor, "connection");
- shutdownExecutor(forwardExecutor, "forward");
+ boolean isStopping() {
+ return !running;
}
- private void shutdownExecutor(ExecutorService executor, String name) {
+ private void shutdownExecutor(ExecutorService executor, String name, Runnable cancelActive) {
if (executor == null) {
return;
}
executor.shutdown();
+ boolean interrupted = false;
try {
- if (!executor.awaitTermination(3, TimeUnit.SECONDS)) {
- executor.shutdownNow();
+ try {
+ if (executor.awaitTermination(3, TimeUnit.SECONDS)) {
+ return;
+ }
+ } catch (InterruptedException ex) {
+ interrupted = true;
+ }
+ cancelActive.run();
+ executor.shutdownNow();
+ try {
if (!executor.awaitTermination(3, TimeUnit.SECONDS)) {
logWarning("Unable to fully shut down " + name + " executor.");
}
+ } catch (InterruptedException ex) {
+ interrupted = true;
+ }
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
}
- } catch (InterruptedException ex) {
- executor.shutdownNow();
- Thread.currentThread().interrupt();
}
}
@@ -192,95 +223,119 @@ public void run() {
+ "Set DisableV1: true to require token-authenticated V2 votes.");
}
- int connectionWorkerCount = getConnectionWorkerCount();
- connectionExecutor = new ThreadPoolExecutor(connectionWorkerCount, connectionWorkerCount, 0L,
- TimeUnit.MILLISECONDS, new ArrayBlockingQueue(getConnectionQueueCapacity()),
- new ThreadFactory() {
- private int id = 1;
+ synchronized (lifecycleLock) {
+ if (!running) {
+ return;
+ }
+ connectionExecutor = createExecutor(getConnectionWorkerCount(), getConnectionQueueCapacity(),
+ "Votifier-Connection-");
+ forwardExecutor = createExecutor(getForwardWorkerCount(), getForwardQueueCapacity(), "Votifier-Forwarder-");
+ }
- @Override
- public Thread newThread(Runnable r) {
- Thread thread = new Thread(r, "Votifier-Connection-" + id++);
- thread.setDaemon(true);
- return thread;
+ VoteConnectionHandler handler = new VoteConnectionHandler(this, throttleService);
+ try {
+ while (running) {
+ try {
+ submitConnection(acceptSocket(), handler);
+ } catch (SocketException ex) {
+ if (running) {
+ logWarning("Connection error while accepting vote socket: " + VoteLogSafety.exceptionType(ex));
}
- }, new ThreadPoolExecutor.AbortPolicy());
+ if (server.isClosed()) {
+ break;
+ }
+ } catch (Exception ex) {
+ if (running) {
+ logWarning("Error accepting vote connection: " + VoteLogSafety.exceptionType(ex));
+ }
+ }
+ }
+ } finally {
+ if (running) {
+ shutdown();
+ }
+ }
+ }
- int forwardWorkerCount = getForwardWorkerCount();
- forwardExecutor = new ThreadPoolExecutor(forwardWorkerCount, forwardWorkerCount, 0L, TimeUnit.MILLISECONDS,
- new ArrayBlockingQueue(getForwardQueueCapacity()), new ThreadFactory() {
+ private ThreadPoolExecutor createExecutor(int workers, int capacity, String threadPrefix) {
+ return new ThreadPoolExecutor(workers, workers, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(capacity),
+ new ThreadFactory() {
private int id = 1;
@Override
- public Thread newThread(Runnable r) {
- Thread thread = new Thread(r, "Votifier-Forwarder-" + id++);
+ public Thread newThread(Runnable work) {
+ Thread thread = new Thread(work, threadPrefix + id++);
thread.setDaemon(true);
return thread;
}
- }, new ThreadPoolExecutor.CallerRunsPolicy());
-
- final VoteConnectionHandler handler = new VoteConnectionHandler(this, throttleService);
-
- while (running) {
- try {
- final Socket socket = acceptSocket();
- final long acceptedAtNanos = System.nanoTime();
+ }, new ThreadPoolExecutor.AbortPolicy());
+ }
+ private void submitConnection(Socket socket, VoteConnectionHandler handler) throws SocketException {
+ long acceptedAtNanos = System.nanoTime();
+ boolean submitted = false;
+ try {
+ socket.setSoTimeout(5000);
+ synchronized (lifecycleLock) {
+ if (!running) {
+ return;
+ }
+ connections.add(socket);
try {
- socket.setSoTimeout(5000);
- } catch (SocketException ex) {
- closeConnection(socket);
- throw ex;
+ connectionExecutor.execute(() -> processConnection(socket, handler, acceptedAtNanos));
+ submitted = true;
+ } finally {
+ if (!submitted) {
+ connections.remove(socket);
+ }
}
+ }
+ } catch (RejectedExecutionException ex) {
+ debug("Rejected vote connection because the connection queue is full.");
+ } finally {
+ if (!submitted) {
+ closeConnection(socket);
+ }
+ }
+ }
+
+ private void processConnection(Socket socket, VoteConnectionHandler handler, long acceptedAtNanos) {
+ try {
+ if (!running) {
+ return;
+ }
+ long queueTimeoutMillis = getConnectionQueueTimeoutMillis();
+ if (queueTimeoutMillis > 0
+ && System.nanoTime() - acceptedAtNanos > TimeUnit.MILLISECONDS.toNanos(queueTimeoutMillis)) {
+ debug("Closed stale vote connection after it exceeded the connection queue deadline.");
+ return;
+ }
+ Vote vote = handler.handle(socket);
+ if (vote != null) {
+ callEvent(vote);
+ submitForward(vote);
+ }
+ } catch (Exception ex) {
+ logWarning("Error processing vote connection: " + VoteLogSafety.exceptionType(ex));
+ } finally {
+ closeConnection(socket);
+ synchronized (lifecycleLock) {
+ connections.remove(socket);
+ }
+ }
+ }
+ private void submitForward(Vote vote) {
+ try {
+ forwardExecutor.execute(() -> {
try {
- connectionExecutor.execute(new Runnable() {
- @Override
- public void run() {
- long queueTimeoutMillis = getConnectionQueueTimeoutMillis();
- if (queueTimeoutMillis > 0 && System.nanoTime() - acceptedAtNanos > TimeUnit.MILLISECONDS
- .toNanos(queueTimeoutMillis)) {
- closeConnection(socket);
- debug("Closed stale vote connection after it exceeded the connection queue deadline.");
- return;
- }
-
- try {
- Vote vote = handler.handle(socket);
- if (vote != null) {
- callEvent(vote);
-
- final Vote forwardVote = vote;
- forwardExecutor.execute(new Runnable() {
- @Override
- public void run() {
- try {
- voteForwarder.forwardVote(forwardVote);
- } catch (Exception ex) {
- logWarning("Error forwarding vote: " + VoteLogSafety.exceptionType(ex));
- }
- }
- });
- }
- } catch (Exception ex) {
- logWarning("Error processing vote connection: " + VoteLogSafety.exceptionType(ex));
- }
- }
- });
- } catch (RejectedExecutionException ex) {
- closeConnection(socket);
- debug("Rejected vote connection because the connection queue is full.");
+ voteForwarder.forwardVote(vote);
+ } catch (Exception ex) {
+ logWarning("Error forwarding vote: " + VoteLogSafety.exceptionType(ex));
}
- } catch (SocketException ex) {
- if (running) {
- logWarning("Connection error while accepting vote socket: " + VoteLogSafety.exceptionType(ex));
- }
- if (server.isClosed()) {
- running = false;
- }
- } catch (Exception ex) {
- logWarning("Error accepting vote connection: " + VoteLogSafety.exceptionType(ex));
- }
+ });
+ } catch (RejectedExecutionException ex) {
+ throttleService.logWarning(this, "forward-queue", "Unable to queue vote forwarding: forwarding executor is full or stopping.");
}
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 79491c8..d5966a6 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -1,10 +1,16 @@
package com.bencodez.votifierplus.tests;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.Socket;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.lang.reflect.Method;
+import java.util.concurrent.LinkedBlockingQueue;
import java.security.Key;
import java.security.KeyPair;
import java.util.Collections;
@@ -65,6 +71,84 @@ public void unexpectedAcceptSocketExceptionWarnsWhileRunning() throws Exception
assertTrue(receiver.getWarnings().size() == 1, () -> "Expected one accept warning, got: " + receiver.getWarnings());
}
+ @Test
+ public void forcedShutdownClosesActiveAndQueuedSockets() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ receiver.pauseProcessing = true;
+ receiver.start();
+ int port = receiver.getServer().getLocalPort();
+ try (Socket active = new Socket("127.0.0.1", port);
+ Socket queued = new Socket("127.0.0.1", port)) {
+ assertTrue(receiver.processing.await(2, TimeUnit.SECONDS));
+ Socket first = receiver.accepted.poll(2, TimeUnit.SECONDS);
+ Socket second = receiver.accepted.poll(2, TimeUnit.SECONDS);
+ assertNotNull(first);
+ assertNotNull(second);
+ assertTrue(receiver.thirdAccept.await(2, TimeUnit.SECONDS), "second socket was not submitted");
+ var retiring = new Thread(() -> {
+ Thread.currentThread().interrupt();
+ receiver.shutdown();
+ });
+ retiring.start();
+ retiring.join(5000);
+ assertFalse(retiring.isAlive());
+ assertTrue(first.isClosed());
+ assertTrue(second.isClosed());
+ assertTrue(retiring.isInterrupted());
+ }
+ }
+
+ @Test
+ public void socketAcceptedDuringRetirementIsClosed() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ receiver.pauseAccept = true;
+ receiver.start();
+ try (Socket client = new Socket("127.0.0.1", receiver.getServer().getLocalPort())) {
+ Socket accepted = receiver.accepted.poll(2, TimeUnit.SECONDS);
+ assertNotNull(accepted);
+ try {
+ receiver.shutdown();
+ } finally {
+ receiver.resumeAccept.countDown();
+ }
+ receiver.join(3000);
+ assertFalse(receiver.isAlive());
+ assertTrue(accepted.isClosed());
+ assertEquals(1L, receiver.processing.getCount());
+ }
+ }
+
+ @Test
+ public void fullForwardingQueueNeverRunsTheOutboundJobOnTheSubmittingThread() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ try (ServerSocket backend = new ServerSocket(0, 3, InetAddress.getLoopbackAddress())) {
+ backend.setSoTimeout(2000);
+ receiver.servers = Set.of("test");
+ receiver.target = new ForwardServer(true, backend.getInetAddress().getHostAddress(),
+ backend.getLocalPort(), "", null);
+ receiver.start();
+ waitForAccept();
+ Method submit = VoteReceiver.class.getDeclaredMethod("submitForward", Vote.class);
+ submit.setAccessible(true);
+ Vote vote = new Vote("example.test", "TestVoter", "", "TestTimestamp");
+ submit.invoke(receiver, vote);
+ try (Socket stalled = backend.accept()) {
+ submit.invoke(receiver, vote);
+ submit.invoke(receiver, vote);
+ assertTrue(receiver.getWarnings().stream().anyMatch(warning -> warning.contains("Unable to queue")));
+ var retire = new Thread(() -> {
+ Thread.currentThread().interrupt();
+ receiver.shutdown();
+ });
+ retire.start();
+ retire.join(5000);
+ assertFalse(retire.isAlive());
+ stalled.setSoTimeout(2000);
+ assertEquals(-1, stalled.getInputStream().read());
+ }
+ }
+ }
+
private void waitForAccept() throws InterruptedException {
assertTrue(receiver.awaitingAccept(2, TimeUnit.SECONDS), "Receiver did not reach accept()");
}
@@ -73,6 +157,14 @@ private static final class CapturingVoteReceiver extends VoteReceiver {
private final List warnings = new CopyOnWriteArrayList<>();
private final CountDownLatch accepting = new CountDownLatch(1);
+ private final CountDownLatch processing = new CountDownLatch(1);
+ private final CountDownLatch thirdAccept = new CountDownLatch(3);
+ private final CountDownLatch resumeAccept = new CountDownLatch(1);
+ private final LinkedBlockingQueue accepted = new LinkedBlockingQueue<>();
+ private boolean pauseAccept;
+ private boolean pauseProcessing;
+ private Set servers = Set.of();
+ private ForwardServer target;
private CapturingVoteReceiver() throws Exception {
super("127.0.0.1", 0);
@@ -89,7 +181,27 @@ private boolean awaitingAccept(long timeout, TimeUnit unit) throws InterruptedEx
@Override
protected Socket acceptSocket() throws IOException {
accepting.countDown();
- return super.acceptSocket();
+ thirdAccept.countDown();
+ Socket socket = super.acceptSocket();
+ accepted.add(socket);
+ if (pauseAccept) {
+ try {
+ resumeAccept.await(3, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ return socket;
+ }
+
+ @Override
+ public int getConnectionWorkerCount() {
+ return 1;
+ }
+
+ @Override
+ public int getForwardQueueCapacity() {
+ return 1;
}
@Override
@@ -117,6 +229,16 @@ public void log(String message) {
@Override
public void debug(String message) {
+ if (message.startsWith("Accepted connection")) {
+ processing.countDown();
+ if (pauseProcessing) {
+ try {
+ new CountDownLatch(1).await(4, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
}
@Override
@@ -130,7 +252,7 @@ public String getVersion() {
@Override
public Set getServers() {
- return Collections.emptySet();
+ return servers;
}
@Override
@@ -145,7 +267,7 @@ public Map getTokens() {
@Override
public ForwardServer getServerData(String server) {
- return null;
+ return target;
}
@Override
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index e7f4d4f..aec0339 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -6,9 +6,17 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedReader;
import java.io.StringReader;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
@@ -49,4 +57,54 @@ public void oversizedHandshakeIsStillRejected() {
BufferedReader input = new BufferedReader(new StringReader("X".repeat(513) + "\r\n"));
assertThrows(IllegalStateException.class, () -> readHandshakeLine(input));
}
+
+ @Test
+ public void quietPeerAndCrLookaheadUseTheTotalDeadline() throws Exception {
+ for (String greeting : new String[] {"", "VOTIFIER 2 challenge\r"}) {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ Socket client = new Socket(server.getInetAddress(), server.getLocalPort());
+ Socket peer = server.accept()) {
+ peer.getOutputStream().write(greeting.getBytes(StandardCharsets.UTF_8));
+ assertThrows(SocketTimeoutException.class, () -> readSocketHandshake(client, 250));
+ }
+ }
+ }
+
+ @Test
+ public void trickleTrafficCannotRenewTheHandshakeBudget() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ Socket client = new Socket(server.getInetAddress(), server.getLocalPort());
+ Socket peer = server.accept()) {
+ Thread sender = Thread.ofVirtual().start(() -> {
+ try {
+ for (int i = 0; i < 100; i++) {
+ peer.getOutputStream().write('a');
+ Thread.sleep(30);
+ }
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ } catch (IOException ignored) {
+ // The peer may close when the read budget expires.
+ }
+ });
+ try {
+ long start = System.nanoTime();
+ assertThrows(SocketTimeoutException.class, () -> readSocketHandshake(client, 300));
+ assertTrue(System.nanoTime() - start < TimeUnit.SECONDS.toNanos(2));
+ } finally {
+ sender.interrupt();
+ sender.join(2000);
+ }
+ }
+ }
+
+ private static void readSocketHandshake(Socket socket, int timeoutMillis) throws Throwable {
+ Method parser = VoteForwarder.class.getDeclaredMethod("readHandshakeLine", Socket.class, int.class);
+ parser.setAccessible(true);
+ try {
+ parser.invoke(null, socket, timeoutMillis);
+ } catch (InvocationTargetException failure) {
+ throw failure.getCause();
+ }
+ }
}
From 7ec12e6da6cb46166e8c21837716661b793ed5cd Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Wed, 18 Nov 2026 23:46:24 +0000
Subject: [PATCH 04/15] Keep native binding on the shared vote receiver
---
.../votifier/net/PlatformVoteReceiver.java | 198 -----------------
.../votifier/net/VoteForwarder.java | 3 +-
.../votifier/net/VoteReceiver.java | 199 +++++++++++++++++-
...Test.java => VoteReceiverBindingTest.java} | 19 +-
.../tests/VoteReceiverLifecycleTest.java | 2 +
5 files changed, 208 insertions(+), 213 deletions(-)
delete mode 100644 VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
rename VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/{PlatformVoteReceiverTest.java => VoteReceiverBindingTest.java} (84%)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
deleted file mode 100644
index d7fa284..0000000
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/PlatformVoteReceiver.java
+++ /dev/null
@@ -1,198 +0,0 @@
-package com.vexsoftware.votifier.net;
-
-import java.io.IOException;
-import java.security.Key;
-import java.security.KeyPair;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import com.vexsoftware.votifier.ForwardServer;
-import com.vexsoftware.votifier.model.Vote;
-
-/** Platform-neutral adapter for the shared listener and forwarding runtime. */
-public final class PlatformVoteReceiver extends VoteReceiver {
-
- /**
- * Binds a receiver using explicit per-listener settings. Start it with
- * {@link VoteReceiver#start()} and retire it with {@link VoteReceiver#shutdown()}.
- *
- * The callback is invoked on a connection worker before forwarding and may
- * run concurrently for different votes. It should enqueue platform work on
- * the appropriate scheduler and return promptly. Treat the vote as read-only
- * because forwarding uses the same object. The adapter owns the lifecycle of
- * work it enqueues on its scheduler. The receiver can invoke the callback
- * for connections already admitted while shutdown drains the worker pool.
- * The adapter must gate and drain its scheduler work during disable.
- *
- *
The wire response acknowledges protocol acceptance before this
- * callback. Callback failures are logged and forwarding can still proceed.
- *
- * @param settings listener configuration and protocol policy
- * @param logger logger for the receiver
- * @param onVote callback for a parsed, accepted vote
- * @return bound, unstarted receiver
- * @throws Exception if the listener cannot bind
- */
- public static PlatformVoteReceiver bind(Settings settings, Logger logger, Consumer onVote) throws Exception {
- return new PlatformVoteReceiver(Objects.requireNonNull(settings), Objects.requireNonNull(logger),
- Objects.requireNonNull(onVote));
- }
-
- /**
- * Configuration for one listener. Supply a new configuration and receiver
- * when changing policy. Token support controls the greeting, while disableV1
- * requires V2 authentication. An empty trusted-proxy set trusts no peer.
- */
- public record Settings(String host, int port, String version, boolean tokenSupport, boolean disableV1,
- KeyPair keyPair, Map tokens, Set trustedProxyIps, ThrottleConfig throttle,
- Map forwarding) {
- public Settings {
- Objects.requireNonNull(version);
- if (!disableV1) {
- Objects.requireNonNull(keyPair, "Legacy V1 requires an RSA key pair");
- }
- tokens = Map.copyOf(tokens);
- trustedProxyIps = Set.copyOf(trustedProxyIps);
- Map targets = new LinkedHashMap<>();
- forwarding.forEach((name, target) -> targets.put(Objects.requireNonNull(name), copyTarget(target)));
- forwarding = Collections.unmodifiableMap(targets);
- }
-
- @Override
- public Map forwarding() {
- Map targets = new LinkedHashMap<>();
- forwarding.forEach((name, target) -> targets.put(name, copyTarget(target)));
- return Collections.unmodifiableMap(targets);
- }
-
- @Override
- public String toString() {
- return "PlatformVoteReceiver.Settings";
- }
- }
-
- private static ForwardServer copyTarget(ForwardServer target) {
- return new ForwardServer(target.isEnabled(), target.getHost(), target.getPort(), target.getKey(),
- target.getToken());
- }
-
- private final Settings settings;
- private final Logger logger;
- private final Consumer onVote;
-
- private PlatformVoteReceiver(Settings settings, Logger logger, Consumer onVote) throws Exception {
- super(settings.host(), settings.port());
- this.settings = settings;
- this.logger = logger;
- this.onVote = onVote;
- }
-
- @Override
- public boolean isUseTokens() {
- return settings.tokenSupport();
- }
-
- @Override
- public boolean isDisableV1() {
- return settings.disableV1();
- }
-
- @Override
- public ThrottleConfig getThrottleConfig() {
- return settings.throttle();
- }
-
- @Override
- public Set getTrustedProxyIps() {
- return settings.trustedProxyIps();
- }
-
- @Override
- public void logWarning(String warning) {
- logger.warning(warning);
- }
-
- @Override
- public void logSevere(String message) {
- // The superclass can report bind failures before the adapter is initialized.
- Logger sink = logger == null ? Logger.getLogger(PlatformVoteReceiver.class.getName()) : logger;
- sink.severe(message);
- }
-
- @Override
- public void log(String message) {
- logger.info(message);
- }
-
- @Override
- public void debug(String message) {
- if (logger != null) {
- logger.fine(message);
- }
- }
-
- @Override
- public void debug(Exception exception) {
- logger.log(Level.FINE, "Vote receiver operation failed: {0}", VoteLogSafety.exceptionType(exception));
- }
-
- @Override
- public String getVersion() {
- return settings.version();
- }
-
- @Override
- public Set getServers() {
- return settings.forwarding.keySet();
- }
-
- @Override
- public KeyPair getKeyPair() {
- return settings.keyPair();
- }
-
- @Override
- public Map getTokens() {
- return settings.tokens();
- }
-
- @Override
- public ForwardServer getServerData(String name) {
- ForwardServer target = settings.forwarding.get(name);
- return target == null ? null : copyTarget(target);
- }
-
- @Override
- public void callEvent(Vote vote) {
- try {
- onVote.accept(vote);
- } catch (RuntimeException failure) {
- logger.warning("Vote callback failed: " + VoteLogSafety.exceptionType(failure));
- }
- }
-
- @Override
- public void initialize() throws Exception {
- if (getServer() != null) {
- throw new IllegalStateException("Bind a new receiver to replace this listener");
- }
- try {
- super.initialize();
- } catch (Exception failure) {
- if (getServer() != null) {
- try {
- getServer().close();
- } catch (IOException closeFailure) {
- failure.addSuppressed(closeFailure);
- }
- }
- throw failure;
- }
- }
-}
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 64dcc4a..502b22b 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -123,7 +123,7 @@ public void forwardVote(Vote vote) {
}
}
- void stop() {
+ int stop() {
List sockets;
synchronized (activeSockets) {
stopped = true;
@@ -137,6 +137,7 @@ void stop() {
receiver.debug("Failed to close forwarding socket: " + VoteLogSafety.exceptionType(ex));
}
}
+ return sockets.size();
}
static String readHandshakeLine(Socket socket, int timeoutMillis) throws Exception {
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index 7c2d8be..09cf336 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -73,8 +73,10 @@
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
@@ -82,6 +84,10 @@
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.function.IntSupplier;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.crypto.Cipher;
@@ -119,6 +125,71 @@ public VoteReceiver(String host, int port) throws Exception {
initialize();
}
+ /**
+ * Binds a receiver using explicit per-listener settings. Start it with
+ * {@link VoteReceiver#start()} and retire it with {@link VoteReceiver#shutdown()}.
+ *
+ * The callback is invoked on a connection worker before forwarding and may
+ * run concurrently for different votes. It should enqueue platform work on
+ * the appropriate scheduler and return promptly. Treat the vote as read-only
+ * because forwarding uses the same object. The adapter owns the lifecycle of
+ * work it enqueues on its scheduler. The receiver can invoke the callback
+ * for connections already admitted while shutdown drains the worker pool.
+ * The adapter must gate and drain its scheduler work during disable.
+ *
+ *
The wire response acknowledges protocol acceptance before this
+ * callback. Callback failures are logged and forwarding can still proceed.
+ *
+ * @param settings listener configuration and protocol policy
+ * @param logger logger for the receiver
+ * @param onVote callback for a parsed, accepted vote
+ * @return bound, unstarted receiver
+ * @throws Exception if the listener cannot bind
+ */
+ public static VoteReceiver bind(Settings settings, Logger logger, Consumer onVote) throws Exception {
+ return new ConfiguredReceiver(Objects.requireNonNull(settings), Objects.requireNonNull(logger),
+ Objects.requireNonNull(onVote));
+ }
+
+ /**
+ * Configuration for one listener. Supply a new configuration and receiver
+ * when changing policy. Token support controls the greeting, while disableV1
+ * requires V2 authentication. An empty trusted-proxy set trusts no peer.
+ */
+ public record Settings(String host, int port, String version, boolean tokenSupport, boolean disableV1,
+ KeyPair keyPair, Map tokens, Set trustedProxyIps, ThrottleConfig throttle,
+ Map forwarding) {
+ public Settings {
+ Objects.requireNonNull(version);
+ if (!disableV1) {
+ Objects.requireNonNull(keyPair, "Legacy V1 requires an RSA key pair");
+ }
+ tokens = Map.copyOf(tokens);
+ trustedProxyIps = Set.copyOf(trustedProxyIps);
+ Map targets = new LinkedHashMap<>();
+ forwarding.forEach((name, target) -> targets.put(Objects.requireNonNull(name), copyTarget(target)));
+ forwarding = Collections.unmodifiableMap(targets);
+ }
+
+ @Override
+ public Map forwarding() {
+ Map targets = new LinkedHashMap<>();
+ forwarding.forEach((name, target) -> targets.put(name, copyTarget(target)));
+ return Collections.unmodifiableMap(targets);
+ }
+
+ @Override
+ public String toString() {
+ return "VoteReceiver.Settings";
+ }
+ }
+
+ private static ForwardServer copyTarget(ForwardServer target) {
+ return new ForwardServer(target.isEnabled(), target.getHost(), target.getPort(), target.getKey(),
+ target.getToken());
+ }
+
+
public void initialize() throws Exception {
try {
server = new ServerSocket();
@@ -152,7 +223,7 @@ public void shutdown() {
}
sockets.forEach(this::closeConnection);
try {
- shutdownExecutor(connectionExecutor, "connection", () -> {});
+ shutdownExecutor(connectionExecutor, "connection", null);
} finally {
shutdownExecutor(forwardExecutor, "forward", () -> voteForwarder.stop());
}
@@ -162,7 +233,7 @@ boolean isStopping() {
return !running;
}
- private void shutdownExecutor(ExecutorService executor, String name, Runnable cancelActive) {
+ private void shutdownExecutor(ExecutorService executor, String name, IntSupplier cancelActive) {
if (executor == null) {
return;
}
@@ -177,8 +248,12 @@ private void shutdownExecutor(ExecutorService executor, String name, Runnable ca
} catch (InterruptedException ex) {
interrupted = true;
}
- cancelActive.run();
- executor.shutdownNow();
+ int discarded = executor.shutdownNow().size();
+ int closedSockets = cancelActive == null ? 0 : cancelActive.getAsInt();
+ if (cancelActive != null && (discarded != 0 || closedSockets != 0)) {
+ logWarning("Forced forwarding shutdown: discarded queued jobs=" + discarded
+ + ", closed active sockets=" + closedSockets);
+ }
try {
if (!executor.awaitTermination(3, TimeUnit.SECONDS)) {
logWarning("Unable to fully shut down " + name + " executor.");
@@ -412,4 +487,120 @@ public PublicKey getPublicKey(ForwardServer forwardServer) throws Exception {
public String getChallenge() {
return com.vexsoftware.votifier.crypto.TokenUtil.newToken();
}
+ private static final class ConfiguredReceiver extends VoteReceiver {
+ private final Settings settings;
+ private final Logger logger;
+ private final Consumer onVote;
+
+ private ConfiguredReceiver(Settings settings, Logger logger, Consumer onVote) throws Exception {
+ super(settings.host(), settings.port());
+ this.settings = settings;
+ this.logger = logger;
+ this.onVote = onVote;
+ }
+
+ @Override
+ public boolean isUseTokens() {
+ return settings.tokenSupport();
+ }
+
+ @Override
+ public boolean isDisableV1() {
+ return settings.disableV1();
+ }
+
+ @Override
+ public ThrottleConfig getThrottleConfig() {
+ return settings.throttle();
+ }
+
+ @Override
+ public Set getTrustedProxyIps() {
+ return settings.trustedProxyIps();
+ }
+
+ @Override
+ public void logWarning(String warning) {
+ logger.warning(warning);
+ }
+
+ @Override
+ public void logSevere(String message) {
+ // The superclass can report bind failures before the adapter is initialized.
+ Logger sink = logger == null ? Logger.getLogger(VoteReceiver.class.getName()) : logger;
+ sink.severe(message);
+ }
+
+ @Override
+ public void log(String message) {
+ logger.info(message);
+ }
+
+ @Override
+ public void debug(String message) {
+ if (logger != null) {
+ logger.fine(message);
+ }
+ }
+
+ @Override
+ public void debug(Exception exception) {
+ logger.log(Level.FINE, "Vote receiver operation failed: {0}", VoteLogSafety.exceptionType(exception));
+ }
+
+ @Override
+ public String getVersion() {
+ return settings.version();
+ }
+
+ @Override
+ public Set getServers() {
+ return settings.forwarding.keySet();
+ }
+
+ @Override
+ public KeyPair getKeyPair() {
+ return settings.keyPair();
+ }
+
+ @Override
+ public Map getTokens() {
+ return settings.tokens();
+ }
+
+ @Override
+ public ForwardServer getServerData(String name) {
+ ForwardServer target = settings.forwarding.get(name);
+ return target == null ? null : copyTarget(target);
+ }
+
+ @Override
+ public void callEvent(Vote vote) {
+ try {
+ onVote.accept(vote);
+ } catch (RuntimeException failure) {
+ logger.warning("Vote callback failed: " + VoteLogSafety.exceptionType(failure));
+ }
+ }
+
+ @Override
+ public void initialize() throws Exception {
+ if (getServer() != null) {
+ throw new IllegalStateException("Bind a new receiver to replace this listener");
+ }
+ try {
+ super.initialize();
+ } catch (Exception failure) {
+ if (getServer() != null) {
+ try {
+ getServer().close();
+ } catch (IOException closeFailure) {
+ failure.addSuppressed(closeFailure);
+ }
+ }
+ throw failure;
+ }
+ }
+ }
+
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java
similarity index 84%
rename from VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
rename to VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java
index 6b5bad2..02a9d0d 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/PlatformVoteReceiverTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java
@@ -31,18 +31,17 @@
import com.google.gson.JsonObject;
import com.vexsoftware.votifier.ForwardServer;
import com.vexsoftware.votifier.model.Vote;
-import com.vexsoftware.votifier.net.PlatformVoteReceiver;
import com.vexsoftware.votifier.net.VoteReceiver;
-public class PlatformVoteReceiverTest {
+public class VoteReceiverBindingTest {
@Test
public void boundReceiverDeliversOneAuthenticatedVoteAndReleasesListener() throws Exception {
Key dummyTokenKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
var accepted = new LinkedBlockingQueue();
- var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", false, true,
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", false, true,
null, Map.of("example.test", dummyTokenKey), Set.of(), null, Map.of());
- VoteReceiver bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), accepted::add);
+ VoteReceiver bound = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), accepted::add);
int port = bound.getServer().getLocalPort();
try {
bound.start();
@@ -87,11 +86,11 @@ public void boundReceiverDeliversOneAuthenticatedVoteAndReleasesListener() throw
public void boundReceiverSnapshotsForwardingAuthentication() throws Exception {
Key dummyTokenKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
var target = new ForwardServer(true, "127.0.0.1", 1234, "", dummyTokenKey);
- var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
null, Map.of(), Set.of(), null, Map.of("test", target));
target.setToken(null);
settings.forwarding().get("test").setToken(null);
- VoteReceiver bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {});
+ VoteReceiver bound = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {});
try {
bound.getServerData("test").setToken(null);
assertTrue(bound.getServerData("test").isUseTokens());
@@ -102,9 +101,9 @@ public void boundReceiverSnapshotsForwardingAuthentication() throws Exception {
@Test
public void repeatInitializationPreservesTheBoundSocket() throws Exception {
- var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
null, Map.of(), Set.of(), null, Map.of());
- var bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {});
+ var bound = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {});
try {
ServerSocket original = bound.getServer();
assertThrows(IllegalStateException.class, bound::initialize);
@@ -118,9 +117,9 @@ public void repeatInitializationPreservesTheBoundSocket() throws Exception {
@Test
public void callbackRejectionDoesNotEscapeToTheReceiverForwardingPath() throws Exception {
- var settings = new PlatformVoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true,
null, Map.of(), Set.of(), null, Map.of());
- var bound = PlatformVoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {
+ var bound = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), vote -> {
throw new java.util.concurrent.RejectedExecutionException();
});
try {
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index d5966a6..b1c578a 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -143,6 +143,8 @@ public void fullForwardingQueueNeverRunsTheOutboundJobOnTheSubmittingThread() th
retire.start();
retire.join(5000);
assertFalse(retire.isAlive());
+ assertTrue(receiver.getWarnings().stream().anyMatch(warning ->
+ warning.contains("discarded queued jobs=1, closed active sockets=1")));
stalled.setSoTimeout(2000);
assertEquals(-1, stalled.getInputStream().read());
}
From afe11468077485f6e0b36633df8987fc562aa9c1 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Wed, 18 Nov 2026 23:49:36 +0000
Subject: [PATCH 05/15] Serialize concurrent vote receiver retirement
---
.../votifier/net/VoteReceiver.java | 43 +++++++++++++++++--
.../tests/VoteReceiverLifecycleTest.java | 42 ++++++++++++++++++
2 files changed, 82 insertions(+), 3 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index 09cf336..cc8853c 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -79,6 +79,7 @@
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
@@ -107,6 +108,9 @@ public abstract class VoteReceiver extends Thread {
private volatile boolean running = true;
private final Object lifecycleLock = new Object();
private final Set connections = new HashSet<>();
+ private final CountDownLatch retirementComplete = new CountDownLatch(1);
+ private Thread retirementOwner;
+ private static final int DRAIN_SECONDS = 3;
@Getter
private volatile VoteThrottleService throttleService;
@@ -208,9 +212,32 @@ public void initialize() throws Exception {
* bounded drain windows. Platform-owned callbacks must return promptly.
*/
public void shutdown() {
+ boolean ownsRetirement;
+ synchronized (lifecycleLock) {
+ if (retirementOwner == Thread.currentThread()) {
+ return;
+ }
+ ownsRetirement = retirementOwner == null;
+ if (ownsRetirement) {
+ retirementOwner = Thread.currentThread();
+ running = false;
+ }
+ }
+ if (!ownsRetirement) {
+ awaitRetirement();
+ return;
+ }
+
+ try {
+ retire();
+ } finally {
+ retirementComplete.countDown();
+ }
+ }
+
+ private void retire() {
List sockets;
synchronized (lifecycleLock) {
- running = false;
sockets = List.copyOf(connections);
connections.clear();
}
@@ -229,6 +256,16 @@ public void shutdown() {
}
}
+ private void awaitRetirement() {
+ try {
+ if (!retirementComplete.await(4L * DRAIN_SECONDS, TimeUnit.SECONDS)) {
+ logWarning("Timed out waiting for receiver retirement.");
+ }
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
boolean isStopping() {
return !running;
}
@@ -242,7 +279,7 @@ private void shutdownExecutor(ExecutorService executor, String name, IntSupplier
boolean interrupted = false;
try {
try {
- if (executor.awaitTermination(3, TimeUnit.SECONDS)) {
+ if (executor.awaitTermination(DRAIN_SECONDS, TimeUnit.SECONDS)) {
return;
}
} catch (InterruptedException ex) {
@@ -255,7 +292,7 @@ private void shutdownExecutor(ExecutorService executor, String name, IntSupplier
+ ", closed active sockets=" + closedSockets);
}
try {
- if (!executor.awaitTermination(3, TimeUnit.SECONDS)) {
+ if (!executor.awaitTermination(DRAIN_SECONDS, TimeUnit.SECONDS)) {
logWarning("Unable to fully shut down " + name + " executor.");
}
} catch (InterruptedException ex) {
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index b1c578a..41e792c 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -10,6 +10,7 @@
import java.net.InetAddress;
import java.net.ServerSocket;
import java.lang.reflect.Method;
+import java.lang.reflect.Field;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Key;
import java.security.KeyPair;
@@ -151,6 +152,47 @@ public void fullForwardingQueueNeverRunsTheOutboundJobOnTheSubmittingThread() th
}
}
+ @Test
+ public void concurrentShutdownWaitsForTheRetirementOwner() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ CountDownLatch closing = new CountDownLatch(1);
+ CountDownLatch canClose = new CountDownLatch(1);
+ CountDownLatch secondReturned = new CountDownLatch(1);
+ receiver.getServer().close();
+ Field server = VoteReceiver.class.getDeclaredField("server");
+ server.setAccessible(true);
+ server.set(receiver, new ServerSocket() {
+ @Override
+ public void close() throws IOException {
+ closing.countDown();
+ try {
+ canClose.await(3, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ super.close();
+ }
+ });
+ Thread first = new Thread(receiver::shutdown);
+ Thread second = new Thread(() -> {
+ receiver.shutdown();
+ secondReturned.countDown();
+ });
+ first.start();
+ try {
+ assertTrue(closing.await(2, TimeUnit.SECONDS));
+ second.start();
+ assertFalse(secondReturned.await(200, TimeUnit.MILLISECONDS));
+ } finally {
+ canClose.countDown();
+ first.join(5000);
+ second.join(5000);
+ }
+ assertFalse(first.isAlive());
+ assertFalse(second.isAlive());
+ assertTrue(receiver.getServer().isClosed());
+ }
+
private void waitForAccept() throws InterruptedException {
assertTrue(receiver.awaitingAccept(2, TimeUnit.SECONDS), "Receiver did not reach accept()");
}
From 32fd883768f625fe479acaba0780461c957506cd Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Wed, 18 Nov 2026 23:51:17 +0000
Subject: [PATCH 06/15] Verify that receiver retirement closes the listener
once
---
.../java/com/vexsoftware/votifier/net/VoteReceiver.java | 6 +++---
.../votifierplus/tests/VoteReceiverLifecycleTest.java | 6 +++++-
2 files changed, 8 insertions(+), 4 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index cc8853c..cd1a3b6 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -286,10 +286,10 @@ private void shutdownExecutor(ExecutorService executor, String name, IntSupplier
interrupted = true;
}
int discarded = executor.shutdownNow().size();
- int closedSockets = cancelActive == null ? 0 : cancelActive.getAsInt();
- if (cancelActive != null && (discarded != 0 || closedSockets != 0)) {
+ int socketCloseAttempts = cancelActive == null ? 0 : cancelActive.getAsInt();
+ if (cancelActive != null && (discarded != 0 || socketCloseAttempts != 0)) {
logWarning("Forced forwarding shutdown: discarded queued jobs=" + discarded
- + ", closed active sockets=" + closedSockets);
+ + ", active socket close attempts=" + socketCloseAttempts);
}
try {
if (!executor.awaitTermination(DRAIN_SECONDS, TimeUnit.SECONDS)) {
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 41e792c..16e12b2 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -21,6 +21,7 @@
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -145,7 +146,7 @@ public void fullForwardingQueueNeverRunsTheOutboundJobOnTheSubmittingThread() th
retire.join(5000);
assertFalse(retire.isAlive());
assertTrue(receiver.getWarnings().stream().anyMatch(warning ->
- warning.contains("discarded queued jobs=1, closed active sockets=1")));
+ warning.contains("discarded queued jobs=1, active socket close attempts=1")));
stalled.setSoTimeout(2000);
assertEquals(-1, stalled.getInputStream().read());
}
@@ -158,12 +159,14 @@ public void concurrentShutdownWaitsForTheRetirementOwner() throws Exception {
CountDownLatch closing = new CountDownLatch(1);
CountDownLatch canClose = new CountDownLatch(1);
CountDownLatch secondReturned = new CountDownLatch(1);
+ AtomicInteger listenerCloseCalls = new AtomicInteger();
receiver.getServer().close();
Field server = VoteReceiver.class.getDeclaredField("server");
server.setAccessible(true);
server.set(receiver, new ServerSocket() {
@Override
public void close() throws IOException {
+ listenerCloseCalls.incrementAndGet();
closing.countDown();
try {
canClose.await(3, TimeUnit.SECONDS);
@@ -190,6 +193,7 @@ public void close() throws IOException {
}
assertFalse(first.isAlive());
assertFalse(second.isAlive());
+ assertEquals(1, listenerCloseCalls.get());
assertTrue(receiver.getServer().isClosed());
}
From 3fa23e1c4c0f4d5ec800f9dbfe136863776fe3f6 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 21:53:19 +0000
Subject: [PATCH 07/15] Count forwarding queue rejections while accepting votes
locally
---
.../votifier/net/VoteReceiver.java | 13 ++++-
.../tests/VoteReceiverBindingTest.java | 48 ++++++++++---------
.../tests/VoteReceiverLifecycleTest.java | 36 +++++++++-----
3 files changed, 62 insertions(+), 35 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index cd1a3b6..558daf7 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -85,6 +85,7 @@
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import java.util.logging.Level;
@@ -108,6 +109,7 @@ public abstract class VoteReceiver extends Thread {
private volatile boolean running = true;
private final Object lifecycleLock = new Object();
private final Set connections = new HashSet<>();
+ private final AtomicLong rejectedForwardingJobs = new AtomicLong();
private final CountDownLatch retirementComplete = new CountDownLatch(1);
private Thread retirementOwner;
private static final int DRAIN_SECONDS = 3;
@@ -253,6 +255,10 @@ private void retire() {
shutdownExecutor(connectionExecutor, "connection", null);
} finally {
shutdownExecutor(forwardExecutor, "forward", () -> voteForwarder.stop());
+ long rejected = rejectedForwardingJobs.get();
+ if (rejected != 0) {
+ logWarning("Forwarding queue rejections at receiver retirement: " + rejected);
+ }
}
}
@@ -437,6 +443,8 @@ private void processConnection(Socket socket, VoteConnectionHandler handler, lon
}
}
+ // Protocol OK and local delivery precede best-effort forwarding. A full
+ // queue can lose forwarding but must never make ingress do outbound work.
private void submitForward(Vote vote) {
try {
forwardExecutor.execute(() -> {
@@ -447,7 +455,10 @@ private void submitForward(Vote vote) {
}
});
} catch (RejectedExecutionException ex) {
- throttleService.logWarning(this, "forward-queue", "Unable to queue vote forwarding: forwarding executor is full or stopping.");
+ long rejected = rejectedForwardingJobs.incrementAndGet();
+ throttleService.logWarning(this, "forward-queue",
+ "Unable to queue vote forwarding: forwarding executor is full or stopping. Total rejected jobs: "
+ + rejected);
}
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java
index 02a9d0d..3bf8ebc 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverBindingTest.java
@@ -45,28 +45,7 @@ public void boundReceiverDeliversOneAuthenticatedVoteAndReleasesListener() throw
int port = bound.getServer().getLocalPort();
try {
bound.start();
- try (Socket client = new Socket("127.0.0.1", port)) {
- client.setSoTimeout(5000);
- var reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
- String greeting = reader.readLine();
- assertTrue(greeting.startsWith("VOTIFIER 2 "));
- JsonObject inner = new JsonObject();
- inner.addProperty("serviceName", "example.test");
- inner.addProperty("username", "TestVoter");
- inner.addProperty("address", "127.0.0.1");
- inner.addProperty("timestamp", "TestTimestamp");
- inner.addProperty("challenge", greeting.substring("VOTIFIER 2 ".length()));
- String payload = inner.toString();
-
- Mac mac = Mac.getInstance("HmacSHA256");
- mac.init(dummyTokenKey);
- JsonObject envelope = new JsonObject();
- envelope.addProperty("payload", payload);
- envelope.addProperty("signature", Base64.getEncoder()
- .encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))));
- client.getOutputStream().write((envelope + "\n").getBytes(StandardCharsets.UTF_8));
- assertTrue(reader.readLine().contains("\"status\":\"ok\""));
- }
+ assertVoteAccepted(port, dummyTokenKey);
Vote vote = accepted.poll(5, TimeUnit.SECONDS);
assertNotNull(vote);
assertEquals("TestVoter", vote.getUsername());
@@ -82,6 +61,31 @@ public void boundReceiverDeliversOneAuthenticatedVoteAndReleasesListener() throw
}
}
+ static void assertVoteAccepted(int port, Key dummyTokenKey) throws Exception {
+ try (Socket client = new Socket("127.0.0.1", port)) {
+ client.setSoTimeout(5000);
+ var reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
+ String greeting = reader.readLine();
+ assertTrue(greeting.startsWith("VOTIFIER 2 "));
+ JsonObject inner = new JsonObject();
+ inner.addProperty("serviceName", "example.test");
+ inner.addProperty("username", "TestVoter");
+ inner.addProperty("address", "127.0.0.1");
+ inner.addProperty("timestamp", "TestTimestamp");
+ inner.addProperty("challenge", greeting.substring("VOTIFIER 2 ".length()));
+ String payload = inner.toString();
+
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(dummyTokenKey);
+ JsonObject envelope = new JsonObject();
+ envelope.addProperty("payload", payload);
+ envelope.addProperty("signature", Base64.getEncoder()
+ .encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))));
+ client.getOutputStream().write((envelope + "\n").getBytes(StandardCharsets.UTF_8));
+ assertTrue(reader.readLine().contains("\"status\":\"ok\""));
+ }
+ }
+
@Test
public void boundReceiverSnapshotsForwardingAuthentication() throws Exception {
Key dummyTokenKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 16e12b2..8e26443 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -9,7 +9,6 @@
import java.net.Socket;
import java.net.InetAddress;
import java.net.ServerSocket;
-import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Key;
@@ -23,6 +22,8 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import javax.crypto.KeyGenerator;
+
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -121,23 +122,25 @@ public void socketAcceptedDuringRetirementIsClosed() throws Exception {
}
@Test
- public void fullForwardingQueueNeverRunsTheOutboundJobOnTheSubmittingThread() throws Exception {
+ public void fullForwardingQueueStillAcknowledgesAndDeliversVotesLocally() throws Exception {
receiver = new CapturingVoteReceiver();
try (ServerSocket backend = new ServerSocket(0, 3, InetAddress.getLoopbackAddress())) {
backend.setSoTimeout(2000);
receiver.servers = Set.of("test");
receiver.target = new ForwardServer(true, backend.getInetAddress().getHostAddress(),
backend.getLocalPort(), "", null);
+ receiver.signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
receiver.start();
- waitForAccept();
- Method submit = VoteReceiver.class.getDeclaredMethod("submitForward", Vote.class);
- submit.setAccessible(true);
- Vote vote = new Vote("example.test", "TestVoter", "", "TestTimestamp");
- submit.invoke(receiver, vote);
+ int port = receiver.getServer().getLocalPort();
+ VoteReceiverBindingTest.assertVoteAccepted(port, receiver.signingKey);
try (Socket stalled = backend.accept()) {
- submit.invoke(receiver, vote);
- submit.invoke(receiver, vote);
- assertTrue(receiver.getWarnings().stream().anyMatch(warning -> warning.contains("Unable to queue")));
+ for (int i = 0; i < 3; i++) {
+ VoteReceiverBindingTest.assertVoteAccepted(port, receiver.signingKey);
+ }
+ for (int i = 0; i < 4; i++) {
+ assertNotNull(receiver.votes.poll(2, TimeUnit.SECONDS));
+ }
+ assertTrue(receiver.forwardingRejected.await(2, TimeUnit.SECONDS));
var retire = new Thread(() -> {
Thread.currentThread().interrupt();
receiver.shutdown();
@@ -147,6 +150,8 @@ public void fullForwardingQueueNeverRunsTheOutboundJobOnTheSubmittingThread() th
assertFalse(retire.isAlive());
assertTrue(receiver.getWarnings().stream().anyMatch(warning ->
warning.contains("discarded queued jobs=1, active socket close attempts=1")));
+ assertTrue(receiver.getWarnings().contains("Forwarding queue rejections at receiver retirement: 2"));
+ assertEquals(1L, receiver.getWarnings().stream().filter(warning -> warning.contains("Unable to queue")).count());
stalled.setSoTimeout(2000);
assertEquals(-1, stalled.getInputStream().read());
}
@@ -213,6 +218,9 @@ private static final class CapturingVoteReceiver extends VoteReceiver {
private boolean pauseProcessing;
private Set servers = Set.of();
private ForwardServer target;
+ private Key signingKey;
+ private final LinkedBlockingQueue votes = new LinkedBlockingQueue<>();
+ private final CountDownLatch forwardingRejected = new CountDownLatch(1);
private CapturingVoteReceiver() throws Exception {
super("127.0.0.1", 0);
@@ -254,7 +262,7 @@ public int getForwardQueueCapacity() {
@Override
public boolean isUseTokens() {
- return false;
+ return signingKey != null;
}
@Override
@@ -265,6 +273,9 @@ public ThrottleConfig getThrottleConfig() {
@Override
public void logWarning(String warning) {
warnings.add(warning);
+ if (warning.contains("Unable to queue")) {
+ forwardingRejected.countDown();
+ }
}
@Override
@@ -310,7 +321,7 @@ public KeyPair getKeyPair() {
@Override
public Map getTokens() {
- return Collections.emptyMap();
+ return signingKey == null ? Collections.emptyMap() : Map.of("example.test", signingKey);
}
@Override
@@ -320,6 +331,7 @@ public ForwardServer getServerData(String server) {
@Override
public void callEvent(Vote vote) {
+ votes.add(vote);
}
}
}
From bed47ec1135cb95590d2ba538e350993d9bfb2a7 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 22:04:53 +0000
Subject: [PATCH 08/15] Rate-limit repeated forwarding target failures
---
.../votifier/net/VoteForwarder.java | 9 +-
.../tests/VoteReceiverLifecycleTest.java | 85 +++++++++++++++++++
2 files changed, 92 insertions(+), 2 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 502b22b..043be2e 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -38,6 +38,7 @@ public class VoteForwarder {
private static final int HANDSHAKE_TIMEOUT_MILLIS = 3000;
private final VoteReceiver receiver;
+ private final VoteThrottleService failureLogs = new VoteThrottleService(null);
private final Set activeSockets = new HashSet<>();
private volatile boolean stopped;
@@ -112,8 +113,12 @@ public void forwardVote(Vote vote) {
receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)");
} catch (Exception ex) {
if (!stopped) {
- receiver.log("Failed to forward vote to " + VoteLogSafety.field(name) + ": "
- + VoteLogSafety.exceptionType(ex));
+ String warning = failureLogs.allowLog("forward|" + name,
+ "Failed to forward vote to " + VoteLogSafety.field(name) + ": "
+ + VoteLogSafety.exceptionType(ex));
+ if (warning != null) {
+ receiver.log(warning);
+ }
}
} finally {
synchronized (activeSockets) {
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 8e26443..4d257cb 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -9,6 +9,8 @@
import java.net.Socket;
import java.net.InetAddress;
import java.net.ServerSocket;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.FutureTask;
import java.lang.reflect.Field;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Key;
@@ -31,6 +33,7 @@
import com.vexsoftware.votifier.model.Vote;
import com.vexsoftware.votifier.net.ThrottleConfig;
import com.vexsoftware.votifier.net.VoteReceiver;
+import com.vexsoftware.votifier.net.VoteForwarder;
/** Regression tests for receiver thread lifecycle logging. */
public class VoteReceiverLifecycleTest {
@@ -202,6 +205,84 @@ public void close() throws IOException {
assertTrue(receiver.getServer().isClosed());
}
+ @Test
+ public void listenerExitCannotConfirmRetirementOfANonCooperativeWorker() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ receiver.signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ var callbackThread = new LinkedBlockingQueue();
+ var release = new CountDownLatch(1);
+ receiver.onVote = () -> {
+ callbackThread.add(Thread.currentThread());
+ boolean interrupted = false;
+ try {
+ while (release.getCount() != 0) {
+ try {
+ if (!release.await(10, TimeUnit.SECONDS)) {
+ return;
+ }
+ } catch (InterruptedException ex) {
+ interrupted = true;
+ }
+ }
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ };
+ receiver.start();
+ Thread shutdown = new Thread(() -> {
+ Thread.currentThread().interrupt();
+ receiver.shutdown();
+ });
+ Thread worker = null;
+ try {
+ VoteReceiverBindingTest.assertVoteAccepted(receiver.getServer().getLocalPort(), receiver.signingKey);
+ worker = callbackThread.poll(2, TimeUnit.SECONDS);
+ assertNotNull(worker);
+ shutdown.start();
+ shutdown.join(6000);
+ receiver.join(2000);
+ assertFalse(shutdown.isAlive());
+ assertFalse(receiver.isAlive());
+ assertTrue(worker.isAlive(), "Listener exit does not terminate a callback that ignores interruption");
+ assertTrue(receiver.getWarnings().contains("Unable to fully shut down connection executor."));
+ } finally {
+ release.countDown();
+ if (worker != null) {
+ worker.join(2000);
+ assertFalse(worker.isAlive(), "Cooperating after release lets the same worker retire");
+ }
+ }
+ }
+
+ @Test
+ public void repeatedFailuresAgainstOneTargetShareOneDiagnostic() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ try (ServerSocket backend = new ServerSocket(0, 2, InetAddress.getLoopbackAddress())) {
+ backend.setSoTimeout(3000);
+ receiver.servers = Set.of("test");
+ receiver.target = new ForwardServer(true, backend.getInetAddress().getHostAddress(),
+ backend.getLocalPort(), "", null);
+ var replies = new FutureTask(() -> {
+ for (int i = 0; i < 2; i++) {
+ try (Socket peer = backend.accept()) {
+ peer.getOutputStream().write(("A".repeat(600) + "\n").getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ return null;
+ });
+ Thread.ofVirtual().start(replies);
+ var forwarder = new VoteForwarder(receiver);
+ var vote = new Vote("example.test", "TestVoter", "", "TestTimestamp");
+ forwarder.forwardVote(vote);
+ forwarder.forwardVote(vote);
+ replies.get(5, TimeUnit.SECONDS);
+ assertEquals(1L, receiver.info.stream().filter(message -> message.contains("Failed to forward vote")).count());
+ assertFalse(receiver.info.getFirst().contains("A".repeat(100)));
+ }
+ }
+
private void waitForAccept() throws InterruptedException {
assertTrue(receiver.awaitingAccept(2, TimeUnit.SECONDS), "Receiver did not reach accept()");
}
@@ -209,6 +290,7 @@ private void waitForAccept() throws InterruptedException {
private static final class CapturingVoteReceiver extends VoteReceiver {
private final List warnings = new CopyOnWriteArrayList<>();
+ private final List info = new CopyOnWriteArrayList<>();
private final CountDownLatch accepting = new CountDownLatch(1);
private final CountDownLatch processing = new CountDownLatch(1);
private final CountDownLatch thirdAccept = new CountDownLatch(3);
@@ -219,6 +301,7 @@ private static final class CapturingVoteReceiver extends VoteReceiver {
private Set servers = Set.of();
private ForwardServer target;
private Key signingKey;
+ private Runnable onVote = () -> {};
private final LinkedBlockingQueue votes = new LinkedBlockingQueue<>();
private final CountDownLatch forwardingRejected = new CountDownLatch(1);
@@ -284,6 +367,7 @@ public void logSevere(String message) {
@Override
public void log(String message) {
+ info.add(message);
}
@Override
@@ -332,6 +416,7 @@ public ForwardServer getServerData(String server) {
@Override
public void callEvent(Vote vote) {
votes.add(vote);
+ onVote.run();
}
}
}
From 75d6ff058cb339bd76a65189b5bf0c5af7e998bf Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 22:35:37 +0000
Subject: [PATCH 09/15] Confirm receiver retirement and bound forwarding
attempts
---
.../votifier/net/VoteForwarder.java | 262 +++++++++++++-----
.../votifier/net/VoteReceiver.java | 94 +++++--
.../tests/VoteReceiverLifecycleTest.java | 48 +++-
.../tests/net/VoteForwarderHandshakeTest.java | 169 ++++++++++-
4 files changed, 467 insertions(+), 106 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 043be2e..a30f702 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -1,18 +1,26 @@
package com.vexsoftware.votifier.net;
import java.io.BufferedReader;
-import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.OutputStream;
+import java.io.InputStream;
import java.net.InetSocketAddress;
-import java.net.Socket;
import java.net.SocketTimeoutException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.function.BiFunction;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
@@ -34,16 +42,36 @@ public class VoteForwarder {
private static final String FIELD_TIMESTAMP = "timestamp";
private static final String FIELD_CHALLENGE = "challenge";
private static final int MAX_HANDSHAKE_CHARS = 512;
+ private static final int ATTEMPT_TIMEOUT_MILLIS = 5000;
private static final int CONNECT_TIMEOUT_MILLIS = 1000;
private static final int HANDSHAKE_TIMEOUT_MILLIS = 3000;
private final VoteReceiver receiver;
private final VoteThrottleService failureLogs = new VoteThrottleService(null);
- private final Set activeSockets = new HashSet<>();
+ private final Map activeChannels = new HashMap<>();
+ private final Set> pendingResolutions = new HashSet<>();
+ private final ThreadPoolExecutor resolver;
+ private final BiFunction resolveAddress;
private volatile boolean stopped;
public VoteForwarder(VoteReceiver receiver) {
+ this(receiver, receiver.getForwardWorkerCount());
+ }
+
+ VoteForwarder(VoteReceiver receiver, int workers) {
+ this(receiver, workers, InetSocketAddress::new);
+ }
+
+ VoteForwarder(VoteReceiver receiver, int workers, BiFunction resolveAddress) {
this.receiver = receiver;
+ this.resolveAddress = resolveAddress;
+ resolver = new ThreadPoolExecutor(workers, workers, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workers),
+ work -> {
+ Thread thread = new Thread(work, "Votifier-Resolver");
+ thread.setDaemon(true);
+ return thread;
+ }, new ThreadPoolExecutor.AbortPolicy());
+ resolver.allowCoreThreadTimeOut(true);
}
public void forwardVote(Vote vote) {
@@ -60,58 +88,76 @@ public void forwardVote(Vote vote) {
receiver.debug("Preparing to forward vote to: " + VoteLogSafety.field(name) + ", tokens mode: " + server.isUseTokens());
- Socket socket = new Socket();
- try (socket) {
- synchronized (activeSockets) {
- if (stopped) {
- return;
+ long deadline = deadlineAfter(ATTEMPT_TIMEOUT_MILLIS);
+ try (SocketChannel channel = SocketChannel.open(); Selector selector = Selector.open()) {
+ try {
+ synchronized (activeChannels) {
+ if (stopped) {
+ return;
+ }
+ activeChannels.put(channel, selector);
}
- activeSockets.add(socket);
- }
- socket.connect(new InetSocketAddress(server.getHost(), server.getPort()), CONNECT_TIMEOUT_MILLIS);
- String greeting = readHandshakeLine(socket, HANDSHAKE_TIMEOUT_MILLIS);
- OutputStream out = socket.getOutputStream();
- receiver.debug("Received handshake from " + VoteLogSafety.field(name)
- + " (" + (greeting == null ? 0 : greeting.length()) + " chars)");
-
- byte[] payload;
- if (server.isUseTokens()) {
- String[] parts = greeting.split(" ");
- if (parts.length < 3 || !HANDSHAKE_PREFIX.equals(parts[0]) || !HANDSHAKE_V2.equals(parts[1])) {
- throw new IllegalStateException("Invalid token-mode handshake");
+ InetSocketAddress address = resolve(server, deadline);
+ channel.configureBlocking(false);
+ long connectDeadline = limitedDeadline(deadline, CONNECT_TIMEOUT_MILLIS);
+ remaining(connectDeadline);
+ if (!channel.connect(address)) {
+ while (!channel.finishConnect()) {
+ awaitReady(channel, selector, SelectionKey.OP_CONNECT, connectDeadline);
+ }
}
+ remaining(connectDeadline);
+ long greetingDeadline = limitedDeadline(deadline, HANDSHAKE_TIMEOUT_MILLIS);
+ String greeting = readChannelGreeting(channel, selector, greetingDeadline);
+ receiver.debug("Received handshake from " + VoteLogSafety.field(name)
+ + " (" + (greeting == null ? 0 : greeting.length()) + " chars)");
- String challenge = parts[2];
+ byte[] payload;
+ if (server.isUseTokens()) {
+ String[] parts = greeting.split(" ");
+ if (parts.length < 3 || !HANDSHAKE_PREFIX.equals(parts[0]) || !HANDSHAKE_V2.equals(parts[1])) {
+ throw new IllegalStateException("Invalid token-mode handshake");
+ }
- JsonObject inner = new JsonObject();
- inner.addProperty(FIELD_SERVICE_NAME, vote.getServiceName());
- inner.addProperty(FIELD_USERNAME, vote.getUsername());
- inner.addProperty(FIELD_ADDRESS, vote.getAddress());
- inner.addProperty(FIELD_TIMESTAMP, vote.getTimeStamp());
- inner.addProperty(FIELD_CHALLENGE, challenge);
+ String challenge = parts[2];
- String innerJson = inner.toString();
+ JsonObject inner = new JsonObject();
+ inner.addProperty(FIELD_SERVICE_NAME, vote.getServiceName());
+ inner.addProperty(FIELD_USERNAME, vote.getUsername());
+ inner.addProperty(FIELD_ADDRESS, vote.getAddress());
+ inner.addProperty(FIELD_TIMESTAMP, vote.getTimeStamp());
+ inner.addProperty(FIELD_CHALLENGE, challenge);
- Mac mac = Mac.getInstance("HmacSHA256");
- mac.init(server.getToken());
- String sig = Base64.getEncoder()
- .encodeToString(mac.doFinal(innerJson.getBytes(StandardCharsets.UTF_8)));
+ String innerJson = inner.toString();
- JsonObject outer = new JsonObject();
- outer.addProperty(FIELD_PAYLOAD, innerJson);
- outer.addProperty(FIELD_SIGNATURE, sig);
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(server.getToken());
+ String sig = Base64.getEncoder()
+ .encodeToString(mac.doFinal(innerJson.getBytes(StandardCharsets.UTF_8)));
- payload = (outer.toString() + "\r\n").getBytes(StandardCharsets.UTF_8);
- } else {
- String voteString = String.join("\n", OPCODE_VOTE, vote.getServiceName(), vote.getUsername(),
- vote.getAddress(), vote.getTimeStamp(), "") + "\n";
- payload = receiver.encrypt(voteString.getBytes(StandardCharsets.UTF_8), receiver.getPublicKey(server));
- }
+ JsonObject outer = new JsonObject();
+ outer.addProperty(FIELD_PAYLOAD, innerJson);
+ outer.addProperty(FIELD_SIGNATURE, sig);
+
+ payload = (outer.toString() + "\r\n").getBytes(StandardCharsets.UTF_8);
+ } else {
+ String voteString = String.join("\n", OPCODE_VOTE, vote.getServiceName(), vote.getUsername(),
+ vote.getAddress(), vote.getTimeStamp(), "") + "\n";
+ payload = receiver.encrypt(voteString.getBytes(StandardCharsets.UTF_8), receiver.getPublicKey(server));
+ }
- out.write(payload);
- out.flush();
- receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)");
+ writePayload(channel, selector, payload, deadline);
+ receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)");
+ } finally {
+ synchronized (activeChannels) {
+ activeChannels.remove(channel);
+ }
+ }
} catch (Exception ex) {
+ if (ex instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ return;
+ }
if (!stopped) {
String warning = failureLogs.allowLog("forward|" + name,
"Failed to forward vote to " + VoteLogSafety.field(name) + ": "
@@ -120,51 +166,129 @@ public void forwardVote(Vote vote) {
receiver.log(warning);
}
}
- } finally {
- synchronized (activeSockets) {
- activeSockets.remove(socket);
+ }
+ }
+ }
+
+ private InetSocketAddress resolve(ForwardServer target, long deadline) throws Exception {
+ remaining(deadline);
+ var request = new FutureTask<>(() -> resolveAddress.apply(target.getHost(), target.getPort()));
+ try {
+ synchronized (activeChannels) {
+ if (stopped) {
+ throw new IOException("Forwarding has stopped");
}
+ resolver.execute(request);
+ pendingResolutions.add(request);
+ }
+ return request.get(remaining(deadline), TimeUnit.NANOSECONDS);
+ } finally {
+ request.cancel(true);
+ resolver.remove(request);
+ synchronized (activeChannels) {
+ pendingResolutions.remove(request);
}
}
}
int stop() {
- List sockets;
- synchronized (activeSockets) {
+ Map channels;
+ List> requests;
+ synchronized (activeChannels) {
stopped = true;
- sockets = List.copyOf(activeSockets);
- activeSockets.clear();
+ channels = Map.copyOf(activeChannels);
+ activeChannels.clear();
+ requests = List.copyOf(pendingResolutions);
+ pendingResolutions.clear();
+ }
+ requests.forEach(request -> request.cancel(true));
+ for (Runnable queued : resolver.shutdownNow()) {
+ ((FutureTask>) queued).cancel(false);
}
- for (Socket socket : sockets) {
+ for (var entry : channels.entrySet()) {
+ entry.getValue().wakeup();
try {
- socket.close();
+ entry.getKey().close();
} catch (IOException ex) {
receiver.debug("Failed to close forwarding socket: " + VoteLogSafety.exceptionType(ex));
}
}
- return sockets.size();
+ return channels.size();
}
- static String readHandshakeLine(Socket socket, int timeoutMillis) throws Exception {
- long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
- // The decoder can make multiple reads to produce one character. Apply the
- // remaining budget at each socket read, including CR lookahead.
- var input = new FilterInputStream(socket.getInputStream()) {
+ boolean isTerminated() {
+ return resolver.isTerminated();
+ }
+
+ private static long deadlineAfter(int timeoutMillis) {
+ return System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+ }
+
+ private static long limitedDeadline(long overallDeadline, int timeoutMillis) {
+ long now = System.nanoTime();
+ return now + Math.min(overallDeadline - now, TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
+ }
+
+ private static long remaining(long deadline) throws IOException {
+ if (Thread.currentThread().isInterrupted()) {
+ throw new java.io.InterruptedIOException("Forwarding interrupted");
+ }
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ throw new SocketTimeoutException("Forwarding attempt timed out");
+ }
+ return remaining;
+ }
+
+ private static void awaitReady(SocketChannel channel, Selector selector, int operation, long deadline)
+ throws IOException {
+ SelectionKey key = channel.keyFor(selector);
+ if (key == null) {
+ channel.register(selector, operation);
+ } else {
+ key.interestOps(operation);
+ }
+ selector.select(Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining(deadline))));
+ selector.selectedKeys().clear();
+ remaining(deadline);
+ }
+
+ private static void writePayload(SocketChannel channel, Selector selector, byte[] payload, long deadline)
+ throws IOException {
+ ByteBuffer bytes = ByteBuffer.wrap(payload);
+ while (bytes.hasRemaining()) {
+ remaining(deadline);
+ if (channel.write(bytes) == 0) {
+ awaitReady(channel, selector, SelectionKey.OP_WRITE, deadline);
+ }
+ }
+ remaining(deadline);
+ }
+
+ private static String readChannelGreeting(SocketChannel channel, Selector selector, long deadline) throws Exception {
+ var input = new InputStream() {
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
- long remaining = deadline - System.nanoTime();
- if (remaining <= 0) {
- throw new SocketTimeoutException("Forward handshake timed out");
+ ByteBuffer buffer = ByteBuffer.wrap(bytes, offset, length);
+ while (true) {
+ remaining(deadline);
+ int count = channel.read(buffer);
+ if (count != 0 || length == 0) {
+ return count;
+ }
+ awaitReady(channel, selector, SelectionKey.OP_READ, deadline);
}
- socket.setSoTimeout((int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining)));
- return super.read(bytes, offset, length);
+ }
+
+ @Override
+ public int read() throws IOException {
+ byte[] one = new byte[1];
+ return read(one, 0, 1) < 0 ? -1 : Byte.toUnsignedInt(one[0]);
}
};
var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
String greeting = readHandshakeLine(reader);
- if (deadline - System.nanoTime() <= 0) {
- throw new SocketTimeoutException("Forward handshake timed out");
- }
+ remaining(deadline);
return greeting;
}
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index 558daf7..f7ae7f4 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -112,6 +112,7 @@ public abstract class VoteReceiver extends Thread {
private final AtomicLong rejectedForwardingJobs = new AtomicLong();
private final CountDownLatch retirementComplete = new CountDownLatch(1);
private Thread retirementOwner;
+ private volatile boolean retirementCleanupComplete;
private static final int DRAIN_SECONDS = 3;
@Getter
@@ -197,18 +198,44 @@ private static ForwardServer copyTarget(ForwardServer target) {
public void initialize() throws Exception {
- try {
- server = new ServerSocket();
- server.bind(new InetSocketAddress(host, port));
- debug("Bound to " + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort());
- } catch (Exception ex) {
- logSevere(
- "Error initializing vote receiver. Please verify that the configured IP address and port are not already in use.");
- ex.printStackTrace();
- throw new Exception(ex);
+ synchronized (lifecycleLock) {
+ if (!running) {
+ throw new IllegalStateException("Receiver has been shut down");
+ }
+ try {
+ server = new ServerSocket();
+ server.bind(new InetSocketAddress(host, port));
+ debug("Bound to " + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort());
+ } catch (Exception ex) {
+ logSevere(
+ "Error initializing vote receiver. Please verify that the configured IP address and port are not already in use.");
+ ex.printStackTrace();
+ throw new Exception(ex);
+ }
+ }
+ }
+
+ @Override
+ public void start() {
+ synchronized (lifecycleLock) {
+ if (!running) {
+ throw new IllegalThreadStateException("Receiver has been shut down");
+ }
+ super.start();
}
}
+ /**
+ * Returns whether shutdown cleanup completed and all receiver-owned work has
+ * terminated. Platform scheduler work is outside this receiver's ownership.
+ */
+ public final boolean isRetired() {
+ return retirementCleanupComplete && server != null && server.isClosed() && !isAlive()
+ && (connectionExecutor == null || connectionExecutor.isTerminated())
+ && (forwardExecutor == null || forwardExecutor.isTerminated())
+ && (voteForwarder == null || voteForwarder.isTerminated());
+ }
+
/**
* Closes the listener and all admitted sockets, then waits for workers within
* bounded drain windows. Platform-owned callbacks must return promptly.
@@ -231,21 +258,23 @@ public void shutdown() {
}
try {
- retire();
+ retirementCleanupComplete = retire();
} finally {
retirementComplete.countDown();
}
}
- private void retire() {
+ private boolean retire() {
List sockets;
synchronized (lifecycleLock) {
sockets = List.copyOf(connections);
connections.clear();
}
+ boolean listenerClosed = false;
if (server != null) {
try {
server.close();
+ listenerClosed = server.isClosed();
} catch (IOException ex) {
debug(ex);
}
@@ -254,12 +283,19 @@ private void retire() {
try {
shutdownExecutor(connectionExecutor, "connection", null);
} finally {
- shutdownExecutor(forwardExecutor, "forward", () -> voteForwarder.stop());
+ try {
+ shutdownExecutor(forwardExecutor, "forward", () -> voteForwarder.stop());
+ } finally {
+ if (voteForwarder != null) {
+ voteForwarder.stop();
+ }
+ }
long rejected = rejectedForwardingJobs.get();
if (rejected != 0) {
logWarning("Forwarding queue rejections at receiver retirement: " + rejected);
}
}
+ return listenerClosed;
}
private void awaitRetirement() {
@@ -333,25 +369,23 @@ public int getForwardQueueCapacity() {
@Override
public void run() {
- throttleService = new VoteThrottleService(getThrottleConfig());
- voteForwarder = new VoteForwarder(this);
-
- if (isUseTokens() && !isDisableV1()) {
- logWarning("TokenSupport is enabled, but legacy Votifier V1 votes are still accepted. "
- + "Set DisableV1: true to require token-authenticated V2 votes.");
- }
-
- synchronized (lifecycleLock) {
- if (!running) {
- return;
- }
- connectionExecutor = createExecutor(getConnectionWorkerCount(), getConnectionQueueCapacity(),
- "Votifier-Connection-");
- forwardExecutor = createExecutor(getForwardWorkerCount(), getForwardQueueCapacity(), "Votifier-Forwarder-");
- }
-
- VoteConnectionHandler handler = new VoteConnectionHandler(this, throttleService);
try {
+ synchronized (lifecycleLock) {
+ if (!running) {
+ return;
+ }
+ throttleService = new VoteThrottleService(getThrottleConfig());
+ int forwardWorkers = getForwardWorkerCount();
+ voteForwarder = new VoteForwarder(this, forwardWorkers);
+ connectionExecutor = createExecutor(getConnectionWorkerCount(), getConnectionQueueCapacity(),
+ "Votifier-Connection-");
+ forwardExecutor = createExecutor(forwardWorkers, getForwardQueueCapacity(), "Votifier-Forwarder-");
+ }
+ if (isUseTokens() && !isDisableV1()) {
+ logWarning("TokenSupport is enabled, but legacy Votifier V1 votes are still accepted. "
+ + "Set DisableV1: true to require token-authenticated V2 votes.");
+ }
+ VoteConnectionHandler handler = new VoteConnectionHandler(this, throttleService);
while (running) {
try {
submitConnection(acceptSocket(), handler);
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 4d257cb..8e97ead 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -1,6 +1,7 @@
package com.bencodez.votifierplus.tests;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -245,6 +246,7 @@ public void listenerExitCannotConfirmRetirementOfANonCooperativeWorker() throws
receiver.join(2000);
assertFalse(shutdown.isAlive());
assertFalse(receiver.isAlive());
+ assertFalse(receiver.isRetired());
assertTrue(worker.isAlive(), "Listener exit does not terminate a callback that ignores interruption");
assertTrue(receiver.getWarnings().contains("Unable to fully shut down connection executor."));
} finally {
@@ -252,6 +254,7 @@ public void listenerExitCannotConfirmRetirementOfANonCooperativeWorker() throws
if (worker != null) {
worker.join(2000);
assertFalse(worker.isAlive(), "Cooperating after release lets the same worker retire");
+ assertTrue(receiver.isRetired());
}
}
}
@@ -283,6 +286,48 @@ public void repeatedFailuresAgainstOneTargetShareOneDiagnostic() throws Exceptio
}
}
+ @Test
+ public void shutdownBeforeStartSealsTheInstance() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ assertFalse(receiver.isRetired());
+ receiver.shutdown();
+ assertTrue(receiver.isRetired());
+ assertThrows(IllegalThreadStateException.class, receiver::start);
+ assertThrows(IllegalStateException.class, receiver::initialize);
+ assertTrue(receiver.isRetired());
+ }
+
+ @Test
+ public void partialStartupRetiresTheListenerAndOwnedExecutors() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ receiver.invalidForwardQueue = true;
+ var failure = new LinkedBlockingQueue();
+ receiver.setUncaughtExceptionHandler((thread, error) -> failure.add(error));
+ receiver.start();
+ receiver.join(3000);
+ assertFalse(receiver.isAlive());
+ assertTrue(failure.poll(2, TimeUnit.SECONDS) instanceof IllegalArgumentException);
+ assertTrue(receiver.isRetired());
+ }
+
+ @Test
+ public void failedCloseIsNotSuccessfulRetirement() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ receiver.getServer().close();
+ Field server = VoteReceiver.class.getDeclaredField("server");
+ server.setAccessible(true);
+ server.set(receiver, new ServerSocket() {
+ @Override
+ public void close() throws IOException {
+ super.close();
+ throw new IOException("synthetic cleanup failure");
+ }
+ });
+ receiver.shutdown();
+ assertTrue(receiver.getServer().isClosed());
+ assertFalse(receiver.isRetired());
+ }
+
private void waitForAccept() throws InterruptedException {
assertTrue(receiver.awaitingAccept(2, TimeUnit.SECONDS), "Receiver did not reach accept()");
}
@@ -297,6 +342,7 @@ private static final class CapturingVoteReceiver extends VoteReceiver {
private final CountDownLatch resumeAccept = new CountDownLatch(1);
private final LinkedBlockingQueue accepted = new LinkedBlockingQueue<>();
private boolean pauseAccept;
+ private boolean invalidForwardQueue;
private boolean pauseProcessing;
private Set servers = Set.of();
private ForwardServer target;
@@ -340,7 +386,7 @@ public int getConnectionWorkerCount() {
@Override
public int getForwardQueueCapacity() {
- return 1;
+ return invalidForwardQueue ? 0 : 1;
}
@Override
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index aec0339..6343c6e 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -12,10 +12,32 @@
import java.io.StringReader;
import java.io.IOException;
import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.function.BiFunction;
+import com.vexsoftware.votifier.ForwardServer;
+import com.vexsoftware.votifier.net.VoteReceiver;
import java.nio.charset.StandardCharsets;
+import java.security.KeyPairGenerator;
+import java.util.Base64;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Logger;
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.Mac;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.vexsoftware.votifier.model.Vote;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
@@ -62,7 +84,7 @@ public void oversizedHandshakeIsStillRejected() {
public void quietPeerAndCrLookaheadUseTheTotalDeadline() throws Exception {
for (String greeting : new String[] {"", "VOTIFIER 2 challenge\r"}) {
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
- Socket client = new Socket(server.getInetAddress(), server.getLocalPort());
+ SocketChannel client = SocketChannel.open(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
Socket peer = server.accept()) {
peer.getOutputStream().write(greeting.getBytes(StandardCharsets.UTF_8));
assertThrows(SocketTimeoutException.class, () -> readSocketHandshake(client, 250));
@@ -73,7 +95,7 @@ public void quietPeerAndCrLookaheadUseTheTotalDeadline() throws Exception {
@Test
public void trickleTrafficCannotRenewTheHandshakeBudget() throws Exception {
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
- Socket client = new Socket(server.getInetAddress(), server.getLocalPort());
+ SocketChannel client = SocketChannel.open(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
Socket peer = server.accept()) {
Thread sender = Thread.ofVirtual().start(() -> {
try {
@@ -98,11 +120,146 @@ public void trickleTrafficCannotRenewTheHandshakeBudget() throws Exception {
}
}
- private static void readSocketHandshake(Socket socket, int timeoutMillis) throws Throwable {
- Method parser = VoteForwarder.class.getDeclaredMethod("readHandshakeLine", Socket.class, int.class);
- parser.setAccessible(true);
+ @Test
+ public void stalledPayloadWriteExpiresAfterPartialProgress() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ SocketChannel client = SocketChannel.open(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
+ Socket peer = server.accept();
+ Selector selector = Selector.open()) {
+ client.socket().setSendBufferSize(4096);
+ client.configureBlocking(false);
+ Method write = VoteForwarder.class.getDeclaredMethod("writePayload",
+ SocketChannel.class, Selector.class, byte[].class, long.class);
+ write.setAccessible(true);
+ assertThrows(SocketTimeoutException.class, () -> call(write, null, client, selector,
+ new byte[4 * 1024 * 1024], System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(300)));
+ peer.setSoTimeout(1000);
+ assertEquals(0, peer.getInputStream().read());
+ }
+ }
+
+ @Test
+ public void queuedResolutionExpiresWithoutFreeingTheRunningResolverSlot() throws Throwable {
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ BiFunction stubbornResolver = (host, port) -> {
+ entered.countDown();
+ for (;;) {
+ try {
+ release.await();
+ return new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
+ } catch (InterruptedException ignored) {
+ // Model a native resolver that ignores interruption.
+ }
+ }
+ };
+ var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class, BiFunction.class);
+ constructor.setAccessible(true);
+ VoteForwarder forwarder = constructor.newInstance(null, 1, stubbornResolver);
+ var resolverField = VoteForwarder.class.getDeclaredField("resolver");
+ resolverField.setAccessible(true);
+ var resolver = (ThreadPoolExecutor) resolverField.get(forwarder);
+ Method resolve = VoteForwarder.class.getDeclaredMethod("resolve", ForwardServer.class, long.class);
+ resolve.setAccessible(true);
+ Method stop = VoteForwarder.class.getDeclaredMethod("stop");
+ stop.setAccessible(true);
+ var target = new ForwardServer(true, "example.test", 1234, "", null);
try {
- parser.invoke(null, socket, timeoutMillis);
+ assertThrows(TimeoutException.class, () -> call(resolve, forwarder, target,
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(300)));
+ assertTrue(entered.await(1, TimeUnit.SECONDS));
+ assertEquals(1, resolver.getActiveCount());
+ var queued = new FutureTask(() -> {
+ assertThrows(TimeoutException.class, () -> call(resolve, forwarder, target,
+ System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
+ return null;
+ });
+ Thread.ofVirtual().start(queued);
+ long waitUntil = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(500);
+ while (resolver.getQueue().isEmpty() && System.nanoTime() < waitUntil) {
+ Thread.sleep(1);
+ }
+ assertEquals(1, resolver.getQueue().size());
+ assertThrows(RejectedExecutionException.class, () -> call(resolve, forwarder, target,
+ System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
+ queued.get(2, TimeUnit.SECONDS);
+ assertEquals(0, resolver.getQueue().size());
+ call(stop, forwarder);
+ assertTrue(resolver.isShutdown());
+ assertTrue(!resolver.isTerminated());
+ } finally {
+ release.countDown();
+ call(stop, forwarder);
+ assertTrue(resolver.awaitTermination(2, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ public void forwardingPreservesAuthenticatedAndLegacyWirePayloads() throws Exception {
+ var signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ var rsa = KeyPairGenerator.getInstance("RSA");
+ rsa.initialize(2048);
+ var pair = rsa.generateKeyPair();
+ var vote = new Vote("example.test", "TestVoter", "127.0.0.1", "TestTimestamp");
+ for (boolean authenticated : new boolean[] {false, true}) {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ server.setSoTimeout(2000);
+ var target = new ForwardServer(true, server.getInetAddress().getHostAddress(), server.getLocalPort(),
+ Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()), authenticated ? signingKey : null);
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
+ Map.of(), Set.of(), null, Map.of("test", target));
+ var receiver = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), accepted -> {});
+ var peerResult = new FutureTask(() -> {
+ try (Socket peer = server.accept()) {
+ peer.setSoTimeout(3000);
+ var greeting = authenticated ? "VOTIFIER 2 challenge-é\r\n" : "VOTIFIER 1\r\n";
+ peer.getOutputStream().write(greeting.getBytes(StandardCharsets.UTF_8));
+ return peer.getInputStream().readAllBytes();
+ }
+ });
+ Thread.ofVirtual().start(peerResult);
+ try {
+ new VoteForwarder(receiver).forwardVote(vote);
+ byte[] received = peerResult.get(4, TimeUnit.SECONDS);
+ if (authenticated) {
+ var body = new String(received, StandardCharsets.UTF_8);
+ assertTrue(body.endsWith("\r\n"));
+ JsonObject envelope = JsonParser.parseString(body).getAsJsonObject();
+ String payload = envelope.get("payload").getAsString();
+ assertEquals("{\"serviceName\":\"example.test\",\"username\":\"TestVoter\","
+ + "\"address\":\"127.0.0.1\",\"timestamp\":\"TestTimestamp\",\"challenge\":\"challenge-é\"}", payload);
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(signingKey);
+ assertEquals(Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))),
+ envelope.get("signature").getAsString());
+ } else {
+ Cipher cipher = Cipher.getInstance("RSA");
+ cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
+ assertEquals("VOTE\nexample.test\nTestVoter\n127.0.0.1\nTestTimestamp\n\n",
+ new String(cipher.doFinal(received), StandardCharsets.UTF_8));
+ }
+ } finally {
+ receiver.shutdown();
+ }
+ }
+ }
+ }
+
+ private static Object call(Method method, Object receiver, Object... arguments) throws Throwable {
+ try {
+ return method.invoke(receiver, arguments);
+ } catch (InvocationTargetException failure) {
+ throw failure.getCause();
+ }
+ }
+
+ private static void readSocketHandshake(SocketChannel channel, int timeoutMillis) throws Throwable {
+ Method parser = VoteForwarder.class.getDeclaredMethod("readChannelGreeting",
+ SocketChannel.class, Selector.class, long.class);
+ parser.setAccessible(true);
+ channel.configureBlocking(false);
+ try (Selector selector = Selector.open()) {
+ parser.invoke(null, channel, selector, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
} catch (InvocationTargetException failure) {
throw failure.getCause();
}
From cd7a6cde6ce06ae7b0d45258fd2bf84f578f50d6 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 22:39:18 +0000
Subject: [PATCH 10/15] Fence retirement when socket cleanup fails
---
.../votifier/net/VoteForwarder.java | 3 +-
.../votifier/net/VoteReceiver.java | 38 ++++---
.../tests/VoteReceiverLifecycleTest.java | 107 +++++++++++++++++-
3 files changed, 128 insertions(+), 20 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index a30f702..62b1fd0 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -206,11 +206,12 @@ int stop() {
((FutureTask>) queued).cancel(false);
}
for (var entry : channels.entrySet()) {
- entry.getValue().wakeup();
try {
entry.getKey().close();
} catch (IOException ex) {
receiver.debug("Failed to close forwarding socket: " + VoteLogSafety.exceptionType(ex));
+ } finally {
+ entry.getValue().wakeup();
}
}
return channels.size();
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index f7ae7f4..193eebc 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -113,6 +113,7 @@ public abstract class VoteReceiver extends Thread {
private final CountDownLatch retirementComplete = new CountDownLatch(1);
private Thread retirementOwner;
private volatile boolean retirementCleanupComplete;
+ private volatile boolean connectionCloseFailed;
private static final int DRAIN_SECONDS = 3;
@Getter
@@ -202,13 +203,21 @@ public void initialize() throws Exception {
if (!running) {
throw new IllegalStateException("Receiver has been shut down");
}
+ if (server != null && !server.isClosed()) {
+ throw new IllegalStateException("Receiver already owns a listener");
+ }
+ ServerSocket next = new ServerSocket();
try {
- server = new ServerSocket();
- server.bind(new InetSocketAddress(host, port));
- debug("Bound to " + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort());
+ next.bind(new InetSocketAddress(host, port));
+ debug("Bound to " + next.getInetAddress().getHostAddress() + ":" + next.getLocalPort());
+ server = next;
} catch (Exception ex) {
- logSevere(
- "Error initializing vote receiver. Please verify that the configured IP address and port are not already in use.");
+ try {
+ next.close();
+ } catch (IOException closeFailure) {
+ ex.addSuppressed(closeFailure);
+ }
+ logSevere("Error initializing vote receiver. Please verify that the configured IP address and port are not already in use.");
ex.printStackTrace();
throw new Exception(ex);
}
@@ -230,7 +239,7 @@ public void start() {
* terminated. Platform scheduler work is outside this receiver's ownership.
*/
public final boolean isRetired() {
- return retirementCleanupComplete && server != null && server.isClosed() && !isAlive()
+ return retirementCleanupComplete && !connectionCloseFailed && server != null && server.isClosed() && !isAlive()
&& (connectionExecutor == null || connectionExecutor.isTerminated())
&& (forwardExecutor == null || forwardExecutor.isTerminated())
&& (voteForwarder == null || voteForwarder.isTerminated());
@@ -509,7 +518,11 @@ protected Socket acceptSocket() throws IOException {
private void closeConnection(Socket socket) {
try {
socket.close();
+ if (!socket.isClosed()) {
+ connectionCloseFailed = true;
+ }
} catch (IOException ex) {
+ connectionCloseFailed = true;
debug(ex);
}
}
@@ -670,18 +683,7 @@ public void initialize() throws Exception {
if (getServer() != null) {
throw new IllegalStateException("Bind a new receiver to replace this listener");
}
- try {
- super.initialize();
- } catch (Exception failure) {
- if (getServer() != null) {
- try {
- getServer().close();
- } catch (IOException closeFailure) {
- failure.addSuppressed(closeFailure);
- }
- }
- throw failure;
- }
+ super.initialize();
}
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 8e97ead..71f146a 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -9,6 +9,8 @@
import java.io.IOException;
import java.net.Socket;
import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.function.BiFunction;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.FutureTask;
@@ -328,6 +330,98 @@ public void close() throws IOException {
assertFalse(receiver.isRetired());
}
+ @Test
+ public void repeatedLegacyInitializePreservesTheOriginalListener() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ ServerSocket original = receiver.getServer();
+ assertThrows(IllegalStateException.class, receiver::initialize);
+ assertTrue(original == receiver.getServer());
+ assertFalse(original.isClosed());
+ receiver.shutdown();
+ assertTrue(original.isClosed());
+ assertTrue(receiver.isRetired());
+ }
+
+ @Test
+ public void admittedSocketCloseFailurePreventsRetirementConfirmation() throws Exception {
+ receiver = new CapturingVoteReceiver();
+ receiver.pauseProcessing = true;
+ var admitted = org.mockito.Mockito.mock(Socket.class);
+ org.mockito.Mockito.doThrow(new IOException("synthetic socket close failure")).when(admitted).close();
+ receiver.syntheticSocket = admitted;
+ receiver.start();
+ assertTrue(receiver.thirdAccept.await(2, TimeUnit.SECONDS));
+ receiver.shutdown();
+ receiver.join(2000);
+ assertFalse(receiver.isAlive());
+ assertFalse(receiver.isRetired());
+ org.mockito.Mockito.verify(admitted, org.mockito.Mockito.atLeastOnce()).close();
+ }
+
+ @Test
+ public void receiverRetainsStuckResolverAfterNormalAndForcedForwardingDrain() throws Exception {
+ for (boolean force : new boolean[] {false, true}) {
+ receiver = new CapturingVoteReceiver();
+ receiver.signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ receiver.servers = Set.of("test");
+ receiver.target = new ForwardServer(true, "example.test", 1234, "", null);
+ receiver.start();
+ waitForAccept();
+ var resolverThread = new LinkedBlockingQueue();
+ var release = new CountDownLatch(1);
+ BiFunction resolve = (host, port) -> {
+ resolverThread.add(Thread.currentThread());
+ while (release.getCount() != 0) {
+ try {
+ if (!release.await(12, TimeUnit.SECONDS)) {
+ break;
+ }
+ } catch (InterruptedException ignored) {
+ // Model a resolver that keeps running after cancellation.
+ }
+ }
+ return new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
+ };
+ var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class, BiFunction.class);
+ constructor.setAccessible(true);
+ var forwarderField = VoteReceiver.class.getDeclaredField("voteForwarder");
+ forwarderField.setAccessible(true);
+ var stopForwarder = VoteForwarder.class.getDeclaredMethod("stop");
+ stopForwarder.setAccessible(true);
+ stopForwarder.invoke(receiver.getVoteForwarder());
+ forwarderField.set(receiver, constructor.newInstance(receiver, 1, resolve));
+ Thread worker = null;
+ try {
+ VoteReceiverBindingTest.assertVoteAccepted(receiver.getServer().getLocalPort(), receiver.signingKey);
+ worker = resolverThread.poll(2, TimeUnit.SECONDS);
+ assertNotNull(worker);
+ if (!force) {
+ assertTrue(receiver.forwardFailure.await(7, TimeUnit.SECONDS));
+ }
+ var shutdown = new Thread(() -> {
+ if (force) {
+ Thread.currentThread().interrupt();
+ }
+ receiver.shutdown();
+ });
+ shutdown.start();
+ shutdown.join(5000);
+ receiver.join(2000);
+ assertFalse(shutdown.isAlive());
+ assertFalse(receiver.isAlive());
+ assertFalse(receiver.isRetired());
+ assertTrue(worker.isAlive());
+ } finally {
+ release.countDown();
+ if (worker != null) {
+ worker.join(2000);
+ }
+ receiver.shutdown();
+ }
+ assertTrue(receiver.isRetired());
+ }
+ }
+
private void waitForAccept() throws InterruptedException {
assertTrue(receiver.awaitingAccept(2, TimeUnit.SECONDS), "Receiver did not reach accept()");
}
@@ -342,6 +436,8 @@ private static final class CapturingVoteReceiver extends VoteReceiver {
private final CountDownLatch resumeAccept = new CountDownLatch(1);
private final LinkedBlockingQueue accepted = new LinkedBlockingQueue<>();
private boolean pauseAccept;
+ private Socket syntheticSocket;
+ private final CountDownLatch forwardFailure = new CountDownLatch(1);
private boolean invalidForwardQueue;
private boolean pauseProcessing;
private Set servers = Set.of();
@@ -367,7 +463,13 @@ private boolean awaitingAccept(long timeout, TimeUnit unit) throws InterruptedEx
protected Socket acceptSocket() throws IOException {
accepting.countDown();
thirdAccept.countDown();
- Socket socket = super.acceptSocket();
+ Socket socket = syntheticSocket;
+ if (socket == null) {
+ socket = super.acceptSocket();
+ } else {
+ syntheticSocket = null;
+ thirdAccept.countDown();
+ }
accepted.add(socket);
if (pauseAccept) {
try {
@@ -414,6 +516,9 @@ public void logSevere(String message) {
@Override
public void log(String message) {
info.add(message);
+ if (message.contains("Failed to forward vote")) {
+ forwardFailure.countDown();
+ }
}
@Override
From d54900b55644611b1c4d2ae672b5e58b529d4130 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 23:10:17 +0000
Subject: [PATCH 11/15] Preserve JVM forwarding routes with bounded socket
closure
---
.../votifier/net/VoteForwarder.java | 452 ++++++++++++------
.../votifier/net/VoteReceiver.java | 5 +-
.../tests/net/VoteForwarderHandshakeTest.java | 314 ++++++++++--
3 files changed, 603 insertions(+), 168 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 62b1fd0..746435c 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -3,23 +3,22 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.InputStream;
+import java.io.FilterInputStream;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
-import java.nio.ByteBuffer;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
+import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.function.Supplier;
import java.util.function.BiFunction;
import java.util.concurrent.TimeUnit;
@@ -48,7 +47,34 @@ public class VoteForwarder {
private final VoteReceiver receiver;
private final VoteThrottleService failureLogs = new VoteThrottleService(null);
- private final Map activeChannels = new HashMap<>();
+ private final Object lifecycleLock = new Object();
+ private final Set attempts = new HashSet<>();
+ private final ScheduledThreadPoolExecutor deadlines;
+ private final ThreadPoolExecutor closers;
+ private final int workers;
+ private final Supplier socketFactory;
+ private int runtimeCalls;
+ private int runtimeTargets;
+ private boolean directCall;
+ private boolean directTarget;
+ private boolean directSealed;
+ private long expiredAttempts;
+
+ private static final class Attempt {
+ final Socket socket;
+ final boolean direct;
+ final String name;
+ ScheduledFuture> timer;
+ boolean ended;
+ boolean closeFinished;
+ boolean closeRejected;
+
+ Attempt(Socket socket, boolean direct, String name) {
+ this.socket = socket;
+ this.direct = direct;
+ this.name = name;
+ }
+ }
private final Set> pendingResolutions = new HashSet<>();
private final ThreadPoolExecutor resolver;
private final BiFunction resolveAddress;
@@ -63,18 +89,75 @@ public VoteForwarder(VoteReceiver receiver) {
}
VoteForwarder(VoteReceiver receiver, int workers, BiFunction resolveAddress) {
+ this(receiver, workers, resolveAddress, Socket::new);
+ }
+
+ VoteForwarder(VoteReceiver receiver, int workers, BiFunction resolveAddress,
+ Supplier socketFactory) {
this.receiver = receiver;
+ this.workers = workers;
this.resolveAddress = resolveAddress;
- resolver = new ThreadPoolExecutor(workers, workers, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workers),
- work -> {
- Thread thread = new Thread(work, "Votifier-Resolver");
- thread.setDaemon(true);
- return thread;
- }, new ThreadPoolExecutor.AbortPolicy());
- resolver.allowCoreThreadTimeOut(true);
+ this.socketFactory = socketFactory;
+ int closeCapacity = Math.addExact(workers, 1);
+ resolver = createPool(workers, "Votifier-Resolver");
+ closers = createPool(closeCapacity, "Votifier-Socket-Close");
+ deadlines = new ScheduledThreadPoolExecutor(1, work -> daemon(work, "Votifier-Deadline"));
+ deadlines.setRemoveOnCancelPolicy(true);
+ deadlines.setKeepAliveTime(1, TimeUnit.SECONDS);
+ deadlines.allowCoreThreadTimeOut(true);
+ }
+
+ private static ThreadPoolExecutor createPool(int workers, String name) {
+ var pool = new ThreadPoolExecutor(workers, workers, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workers),
+ work -> daemon(work, name), new ThreadPoolExecutor.AbortPolicy());
+ pool.allowCoreThreadTimeOut(true);
+ return pool;
+ }
+
+ private static Thread daemon(Runnable work, String name) {
+ Thread thread = new Thread(work, name);
+ thread.setDaemon(true);
+ return thread;
}
public void forwardVote(Vote vote) {
+ forward(vote, true);
+ }
+
+ void forwardQueuedVote(Vote vote) {
+ forward(vote, false);
+ }
+
+ private void forward(Vote vote, boolean direct) {
+ boolean admitted;
+ synchronized (lifecycleLock) {
+ admitted = !stopped && (direct ? !directSealed && !directCall : runtimeCalls < workers);
+ if (admitted) {
+ if (direct) {
+ directCall = true;
+ } else {
+ runtimeCalls++;
+ }
+ }
+ }
+ if (!admitted) {
+ logFailure("admission", "Forwarding call rejected: capacity is full or stopping");
+ return;
+ }
+ try {
+ forwardTargets(vote, direct);
+ } finally {
+ synchronized (lifecycleLock) {
+ if (direct) {
+ directCall = false;
+ } else {
+ runtimeCalls--;
+ }
+ }
+ }
+ }
+
+ private void forwardTargets(Vote vote, boolean direct) {
for (String name : receiver.getServers()) {
if (stopped || Thread.currentThread().isInterrupted()) {
return;
@@ -89,92 +172,202 @@ public void forwardVote(Vote vote) {
receiver.debug("Preparing to forward vote to: " + VoteLogSafety.field(name) + ", tokens mode: " + server.isUseTokens());
long deadline = deadlineAfter(ATTEMPT_TIMEOUT_MILLIS);
- try (SocketChannel channel = SocketChannel.open(); Selector selector = Selector.open()) {
- try {
- synchronized (activeChannels) {
- if (stopped) {
- return;
- }
- activeChannels.put(channel, selector);
- }
- InetSocketAddress address = resolve(server, deadline);
- channel.configureBlocking(false);
- long connectDeadline = limitedDeadline(deadline, CONNECT_TIMEOUT_MILLIS);
- remaining(connectDeadline);
- if (!channel.connect(address)) {
- while (!channel.finishConnect()) {
- awaitReady(channel, selector, SelectionKey.OP_CONNECT, connectDeadline);
- }
- }
- remaining(connectDeadline);
- long greetingDeadline = limitedDeadline(deadline, HANDSHAKE_TIMEOUT_MILLIS);
- String greeting = readChannelGreeting(channel, selector, greetingDeadline);
- receiver.debug("Received handshake from " + VoteLogSafety.field(name)
- + " (" + (greeting == null ? 0 : greeting.length()) + " chars)");
-
- byte[] payload;
- if (server.isUseTokens()) {
- String[] parts = greeting.split(" ");
- if (parts.length < 3 || !HANDSHAKE_PREFIX.equals(parts[0]) || !HANDSHAKE_V2.equals(parts[1])) {
- throw new IllegalStateException("Invalid token-mode handshake");
- }
-
- String challenge = parts[2];
-
- JsonObject inner = new JsonObject();
- inner.addProperty(FIELD_SERVICE_NAME, vote.getServiceName());
- inner.addProperty(FIELD_USERNAME, vote.getUsername());
- inner.addProperty(FIELD_ADDRESS, vote.getAddress());
- inner.addProperty(FIELD_TIMESTAMP, vote.getTimeStamp());
- inner.addProperty(FIELD_CHALLENGE, challenge);
-
- String innerJson = inner.toString();
-
- Mac mac = Mac.getInstance("HmacSHA256");
- mac.init(server.getToken());
- String sig = Base64.getEncoder()
- .encodeToString(mac.doFinal(innerJson.getBytes(StandardCharsets.UTF_8)));
-
- JsonObject outer = new JsonObject();
- outer.addProperty(FIELD_PAYLOAD, innerJson);
- outer.addProperty(FIELD_SIGNATURE, sig);
-
- payload = (outer.toString() + "\r\n").getBytes(StandardCharsets.UTF_8);
- } else {
- String voteString = String.join("\n", OPCODE_VOTE, vote.getServiceName(), vote.getUsername(),
- vote.getAddress(), vote.getTimeStamp(), "") + "\n";
- payload = receiver.encrypt(voteString.getBytes(StandardCharsets.UTF_8), receiver.getPublicKey(server));
+ Attempt attempt = null;
+ try {
+ attempt = registerAttempt(direct, name, deadline);
+ Socket socket = attempt.socket;
+ InetSocketAddress address = resolve(server, deadline);
+ long connectDeadline = limitedDeadline(deadline, CONNECT_TIMEOUT_MILLIS);
+ socket.connect(address, timeoutMillis(connectDeadline));
+ remaining(connectDeadline);
+ long greetingDeadline = limitedDeadline(deadline, HANDSHAKE_TIMEOUT_MILLIS);
+ String greeting = readSocketGreeting(socket, greetingDeadline);
+ receiver.debug("Received handshake from " + VoteLogSafety.field(name)
+ + " (" + (greeting == null ? 0 : greeting.length()) + " chars)");
+
+ byte[] payload;
+ if (server.isUseTokens()) {
+ String[] parts = greeting.split(" ");
+ if (parts.length < 3 || !HANDSHAKE_PREFIX.equals(parts[0]) || !HANDSHAKE_V2.equals(parts[1])) {
+ throw new IllegalStateException("Invalid token-mode handshake");
}
- writePayload(channel, selector, payload, deadline);
+ String challenge = parts[2];
+
+ JsonObject inner = new JsonObject();
+ inner.addProperty(FIELD_SERVICE_NAME, vote.getServiceName());
+ inner.addProperty(FIELD_USERNAME, vote.getUsername());
+ inner.addProperty(FIELD_ADDRESS, vote.getAddress());
+ inner.addProperty(FIELD_TIMESTAMP, vote.getTimeStamp());
+ inner.addProperty(FIELD_CHALLENGE, challenge);
+
+ String innerJson = inner.toString();
+
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(server.getToken());
+ String sig = Base64.getEncoder()
+ .encodeToString(mac.doFinal(innerJson.getBytes(StandardCharsets.UTF_8)));
+
+ JsonObject outer = new JsonObject();
+ outer.addProperty(FIELD_PAYLOAD, innerJson);
+ outer.addProperty(FIELD_SIGNATURE, sig);
+
+ payload = (outer.toString() + "\r\n").getBytes(StandardCharsets.UTF_8);
+ } else {
+ String voteString = String.join("\n", OPCODE_VOTE, vote.getServiceName(), vote.getUsername(),
+ vote.getAddress(), vote.getTimeStamp(), "") + "\n";
+ payload = receiver.encrypt(voteString.getBytes(StandardCharsets.UTF_8), receiver.getPublicKey(server));
+ }
+
+ remaining(deadline);
+ var output = socket.getOutputStream();
+ output.write(payload);
+ output.flush();
+ boolean completed;
+ synchronized (lifecycleLock) {
+ completed = !stopped && !attempt.ended && deadline - System.nanoTime() > 0;
+ finishAttempt(attempt);
+ }
+ if (completed) {
receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)");
- } finally {
- synchronized (activeChannels) {
- activeChannels.remove(channel);
- }
+ } else {
+ logFailure("target|" + name, "Forwarding attempt ended before completion: " + VoteLogSafety.field(name));
}
} catch (Exception ex) {
+ logFailure("target|" + name, "Failed to forward vote to " + VoteLogSafety.field(name) + ": "
+ + VoteLogSafety.exceptionType(ex));
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
return;
}
- if (!stopped) {
- String warning = failureLogs.allowLog("forward|" + name,
- "Failed to forward vote to " + VoteLogSafety.field(name) + ": "
- + VoteLogSafety.exceptionType(ex));
- if (warning != null) {
- receiver.log(warning);
+ } finally {
+ if (attempt != null) {
+ synchronized (lifecycleLock) {
+ finishAttempt(attempt);
+ awaitClose(attempt, deadline);
+ }
+ if (attempt.closeRejected) {
+ logFailure("close|" + name, "Forwarding socket close submission failed");
}
}
}
}
}
+ private Attempt registerAttempt(boolean direct, String name, long deadline) throws Exception {
+ synchronized (lifecycleLock) {
+ while (!stopped && !direct && runtimeTargets == workers) {
+ TimeUnit.NANOSECONDS.timedWait(lifecycleLock, remaining(deadline));
+ }
+ remaining(deadline);
+ if (stopped || (direct && directTarget)) {
+ throw new RejectedExecutionException("Forwarding socket capacity unavailable");
+ }
+ if (direct) {
+ directTarget = true;
+ } else {
+ runtimeTargets++;
+ }
+ Socket socket;
+ try {
+ socket = socketFactory.get();
+ } catch (RuntimeException | Error ex) {
+ releaseTarget(direct);
+ throw ex;
+ }
+ var attempt = new Attempt(socket, direct, name);
+ attempts.add(attempt);
+ try {
+ attempt.timer = deadlines.schedule(() -> expire(attempt), remaining(deadline), TimeUnit.NANOSECONDS);
+ } catch (Exception ex) {
+ finishAttempt(attempt);
+ throw ex;
+ }
+ return attempt;
+ }
+ }
+
+ private void expire(Attempt attempt) {
+ synchronized (lifecycleLock) {
+ if (attempt.ended) {
+ return;
+ }
+ expiredAttempts++;
+ finishAttempt(attempt);
+ }
+ }
+
+ // The only terminal transition and close submission. Caller holds lifecycleLock.
+ private void finishAttempt(Attempt attempt) {
+ if (attempt.ended) {
+ return;
+ }
+ attempt.ended = true;
+ if (attempt.timer != null) {
+ attempt.timer.cancel(false);
+ }
+ try {
+ closers.execute(() -> closeAttempt(attempt));
+ } catch (RejectedExecutionException ex) {
+ attempt.closeRejected = true;
+ attempt.closeFinished = true;
+ lifecycleLock.notifyAll();
+ }
+ }
+
+ private void closeAttempt(Attempt attempt) {
+ try {
+ attempt.socket.close();
+ if (!attempt.socket.isClosed()) {
+ throw new IOException("Forwarding socket remained open");
+ }
+ synchronized (lifecycleLock) {
+ attempt.closeFinished = true;
+ attempts.remove(attempt);
+ releaseTarget(attempt.direct);
+ }
+ } catch (Exception ex) {
+ synchronized (lifecycleLock) {
+ attempt.closeFinished = true;
+ lifecycleLock.notifyAll();
+ }
+ logFailure("close|" + attempt.name, "Forwarding socket close failed: " + VoteLogSafety.exceptionType(ex));
+ }
+ }
+
+ private void releaseTarget(boolean direct) {
+ if (direct) {
+ directTarget = false;
+ } else {
+ runtimeTargets--;
+ }
+ lifecycleLock.notifyAll();
+ }
+
+ private void awaitClose(Attempt attempt, long deadline) {
+ try {
+ while (!stopped && !attempt.closeFinished) {
+ TimeUnit.NANOSECONDS.timedWait(lifecycleLock, remaining(deadline));
+ }
+ } catch (IOException ex) {
+ // Closure retains the target permit beyond the caller deadline.
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ private void logFailure(String key, String message) {
+ String warning = failureLogs.allowLog(key, message);
+ if (warning != null) {
+ receiver.log(warning);
+ }
+ }
+
private InetSocketAddress resolve(ForwardServer target, long deadline) throws Exception {
remaining(deadline);
var request = new FutureTask<>(() -> resolveAddress.apply(target.getHost(), target.getPort()));
try {
- synchronized (activeChannels) {
+ synchronized (lifecycleLock) {
if (stopped) {
throw new IOException("Forwarding has stopped");
}
@@ -185,40 +378,59 @@ private InetSocketAddress resolve(ForwardServer target, long deadline) throws Ex
} finally {
request.cancel(true);
resolver.remove(request);
- synchronized (activeChannels) {
+ synchronized (lifecycleLock) {
pendingResolutions.remove(request);
}
}
}
+ void sealDirectCalls() {
+ synchronized (lifecycleLock) {
+ directSealed = true;
+ }
+ }
+
int stop() {
- Map channels;
+ int cancellations = 0;
+ int rejectedCloses = 0;
+ long expired;
List> requests;
- synchronized (activeChannels) {
+ synchronized (lifecycleLock) {
+ if (stopped) {
+ return 0;
+ }
stopped = true;
- channels = Map.copyOf(activeChannels);
- activeChannels.clear();
+ lifecycleLock.notifyAll();
+ for (Attempt attempt : attempts) {
+ if (!attempt.ended) {
+ finishAttempt(attempt);
+ cancellations++;
+ }
+ if (attempt.closeRejected) {
+ rejectedCloses++;
+ }
+ }
+ expired = expiredAttempts;
requests = List.copyOf(pendingResolutions);
pendingResolutions.clear();
+ deadlines.shutdown();
+ closers.shutdown();
}
requests.forEach(request -> request.cancel(true));
for (Runnable queued : resolver.shutdownNow()) {
((FutureTask>) queued).cancel(false);
}
- for (var entry : channels.entrySet()) {
- try {
- entry.getKey().close();
- } catch (IOException ex) {
- receiver.debug("Failed to close forwarding socket: " + VoteLogSafety.exceptionType(ex));
- } finally {
- entry.getValue().wakeup();
- }
+ if (receiver != null && (expired != 0 || rejectedCloses != 0)) {
+ receiver.logWarning("Forwarding deadline expirations=" + expired + ", rejected socket closes=" + rejectedCloses);
}
- return channels.size();
+ return cancellations;
}
boolean isTerminated() {
- return resolver.isTerminated();
+ synchronized (lifecycleLock) {
+ return stopped && runtimeCalls == 0 && !directCall && attempts.isEmpty()
+ && resolver.isTerminated() && deadlines.isTerminated() && closers.isTerminated();
+ }
}
private static long deadlineAfter(int timeoutMillis) {
@@ -241,50 +453,16 @@ private static long remaining(long deadline) throws IOException {
return remaining;
}
- private static void awaitReady(SocketChannel channel, Selector selector, int operation, long deadline)
- throws IOException {
- SelectionKey key = channel.keyFor(selector);
- if (key == null) {
- channel.register(selector, operation);
- } else {
- key.interestOps(operation);
- }
- selector.select(Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining(deadline))));
- selector.selectedKeys().clear();
- remaining(deadline);
- }
-
- private static void writePayload(SocketChannel channel, Selector selector, byte[] payload, long deadline)
- throws IOException {
- ByteBuffer bytes = ByteBuffer.wrap(payload);
- while (bytes.hasRemaining()) {
- remaining(deadline);
- if (channel.write(bytes) == 0) {
- awaitReady(channel, selector, SelectionKey.OP_WRITE, deadline);
- }
- }
- remaining(deadline);
+ private static int timeoutMillis(long deadline) throws IOException {
+ return (int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining(deadline)));
}
- private static String readChannelGreeting(SocketChannel channel, Selector selector, long deadline) throws Exception {
- var input = new InputStream() {
+ private static String readSocketGreeting(Socket socket, long deadline) throws Exception {
+ var input = new FilterInputStream(socket.getInputStream()) {
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
- ByteBuffer buffer = ByteBuffer.wrap(bytes, offset, length);
- while (true) {
- remaining(deadline);
- int count = channel.read(buffer);
- if (count != 0 || length == 0) {
- return count;
- }
- awaitReady(channel, selector, SelectionKey.OP_READ, deadline);
- }
- }
-
- @Override
- public int read() throws IOException {
- byte[] one = new byte[1];
- return read(one, 0, 1) < 0 ? -1 : Byte.toUnsignedInt(one[0]);
+ socket.setSoTimeout(timeoutMillis(deadline));
+ return super.read(bytes, offset, length);
}
};
var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
index 193eebc..ff822b9 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteReceiver.java
@@ -274,6 +274,9 @@ public void shutdown() {
}
private boolean retire() {
+ if (voteForwarder != null) {
+ voteForwarder.sealDirectCalls();
+ }
List sockets;
synchronized (lifecycleLock) {
sockets = List.copyOf(connections);
@@ -492,7 +495,7 @@ private void submitForward(Vote vote) {
try {
forwardExecutor.execute(() -> {
try {
- voteForwarder.forwardVote(vote);
+ voteForwarder.forwardQueuedVote(vote);
} catch (Exception ex) {
logWarning("Error forwarding vote: " + VoteLogSafety.exceptionType(ex));
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index 6343c6e..48f97ee 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -5,25 +5,35 @@
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedReader;
+import java.io.DataInputStream;
+import java.io.FilterOutputStream;
+import java.io.OutputStream;
+import java.nio.file.Path;
import java.io.StringReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
import java.net.ServerSocket;
import java.net.Socket;
+import java.net.SocketAddress;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CancellationException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.FutureTask;
import java.util.function.BiFunction;
+import java.util.function.Supplier;
+import java.util.concurrent.atomic.AtomicInteger;
import com.vexsoftware.votifier.ForwardServer;
import com.vexsoftware.votifier.net.VoteReceiver;
import java.nio.charset.StandardCharsets;
@@ -84,7 +94,7 @@ public void oversizedHandshakeIsStillRejected() {
public void quietPeerAndCrLookaheadUseTheTotalDeadline() throws Exception {
for (String greeting : new String[] {"", "VOTIFIER 2 challenge\r"}) {
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
- SocketChannel client = SocketChannel.open(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
+ Socket client = new Socket(server.getInetAddress(), server.getLocalPort());
Socket peer = server.accept()) {
peer.getOutputStream().write(greeting.getBytes(StandardCharsets.UTF_8));
assertThrows(SocketTimeoutException.class, () -> readSocketHandshake(client, 250));
@@ -95,7 +105,7 @@ public void quietPeerAndCrLookaheadUseTheTotalDeadline() throws Exception {
@Test
public void trickleTrafficCannotRenewTheHandshakeBudget() throws Exception {
try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
- SocketChannel client = SocketChannel.open(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
+ Socket client = new Socket(server.getInetAddress(), server.getLocalPort());
Socket peer = server.accept()) {
Thread sender = Thread.ofVirtual().start(() -> {
try {
@@ -120,23 +130,6 @@ public void trickleTrafficCannotRenewTheHandshakeBudget() throws Exception {
}
}
- @Test
- public void stalledPayloadWriteExpiresAfterPartialProgress() throws Exception {
- try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
- SocketChannel client = SocketChannel.open(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
- Socket peer = server.accept();
- Selector selector = Selector.open()) {
- client.socket().setSendBufferSize(4096);
- client.configureBlocking(false);
- Method write = VoteForwarder.class.getDeclaredMethod("writePayload",
- SocketChannel.class, Selector.class, byte[].class, long.class);
- write.setAccessible(true);
- assertThrows(SocketTimeoutException.class, () -> call(write, null, client, selector,
- new byte[4 * 1024 * 1024], System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(300)));
- peer.setSoTimeout(1000);
- assertEquals(0, peer.getInputStream().read());
- }
- }
@Test
public void queuedResolutionExpiresWithoutFreeingTheRunningResolverSlot() throws Throwable {
@@ -184,7 +177,20 @@ public void queuedResolutionExpiresWithoutFreeingTheRunningResolverSlot() throws
System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
queued.get(2, TimeUnit.SECONDS);
assertEquals(0, resolver.getQueue().size());
+ var forced = new FutureTask(() -> {
+ assertThrows(CancellationException.class, () -> call(resolve, forwarder, target,
+ System.nanoTime() + TimeUnit.SECONDS.toNanos(4)));
+ return null;
+ });
+ Thread.ofVirtual().start(forced);
+ waitUntil = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(500);
+ while (resolver.getQueue().isEmpty() && System.nanoTime() < waitUntil) {
+ Thread.sleep(1);
+ }
+ assertEquals(1, resolver.getQueue().size());
call(stop, forwarder);
+ forced.get(2, TimeUnit.SECONDS);
+ assertEquals(0, resolver.getQueue().size());
assertTrue(resolver.isShutdown());
assertTrue(!resolver.isTerminated());
} finally {
@@ -245,6 +251,260 @@ public void forwardingPreservesAuthenticatedAndLegacyWirePayloads() throws Excep
}
}
+ @Test
+ public void separateJvmUsesSocksWithoutConnectingToTheTargetDirectly() throws Exception {
+ InetAddress loopback = InetAddress.getByName("127.0.0.1");
+ try (ServerSocket proxy = new ServerSocket(0, 1, loopback);
+ ServerSocket directSentinel = new ServerSocket(0, 1, loopback)) {
+ proxy.setSoTimeout(7000);
+ directSentinel.setSoTimeout(200);
+ String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
+ String classpath = System.getProperty("surefire.test.class.path", System.getProperty("java.class.path"));
+ Process child = new ProcessBuilder(java, "-DsocksProxyHost=127.0.0.1",
+ "-DsocksProxyPort=" + proxy.getLocalPort(), "-DsocksNonProxyHosts=", "-cp", classpath,
+ SocksClient.class.getName(), Integer.toString(directSentinel.getLocalPort()))
+ .redirectErrorStream(true).start();
+ try (Socket peer = proxy.accept()) {
+ peer.setSoTimeout(3000);
+ var in = new DataInputStream(peer.getInputStream());
+ var out = peer.getOutputStream();
+ assertEquals(5, in.readUnsignedByte());
+ int methods = in.readUnsignedByte();
+ in.readNBytes(methods);
+ out.write(new byte[] {5, 0});
+ assertEquals(5, in.readUnsignedByte());
+ assertEquals(1, in.readUnsignedByte());
+ assertEquals(0, in.readUnsignedByte());
+ assertEquals(1, in.readUnsignedByte());
+ assertEquals("127.0.0.1", InetAddress.getByAddress(in.readNBytes(4)).getHostAddress());
+ assertEquals(directSentinel.getLocalPort(), in.readUnsignedShort());
+ out.write(new byte[] {5, 0, 0, 1, 127, 0, 0, 1, 0, 0});
+ out.write("VOTIFIER 2 challenge\r\n".getBytes(StandardCharsets.UTF_8));
+ String received = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ assertTrue(received.contains("TestVoter"));
+ assertTrue(received.endsWith("\r\n"));
+ assertThrows(SocketTimeoutException.class, directSentinel::accept);
+ assertTrue(child.waitFor(5, TimeUnit.SECONDS));
+ assertEquals(0, child.exitValue(), () -> {
+ try {
+ return new String(child.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
+ } catch (IOException ex) {
+ return ex.toString();
+ }
+ });
+ } finally {
+ if (child.isAlive()) {
+ child.destroyForcibly();
+ child.waitFor(2, TimeUnit.SECONDS);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void writeBackpressureExpiresAndClosesTheRealSocket() throws Exception {
+ InetAddress loopback = InetAddress.getByName("127.0.0.1");
+ try (ServerSocket backend = new ServerSocket(0, 1, loopback)) {
+ backend.setReceiveBufferSize(4096);
+ backend.setSoTimeout(3000);
+ var signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ var target = new ForwardServer(true, "127.0.0.1", backend.getLocalPort(), "", signingKey);
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
+ Map.of(), Set.of(), null, Map.of("test", target));
+ var receiver = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), ignored -> {});
+ var writing = new CountDownLatch(1);
+ Socket smallBuffer = new Socket() {
+ @Override
+ public OutputStream getOutputStream() throws IOException {
+ return new FilterOutputStream(super.getOutputStream()) {
+ @Override
+ public void write(byte[] payload) throws IOException {
+ writing.countDown();
+ out.write(payload);
+ }
+ };
+ }
+ };
+ smallBuffer.setSendBufferSize(4096);
+ VoteForwarder forwarder = forwarderWithSockets(receiver, () -> smallBuffer);
+ int submittedBytes = 4 * 1024 * 1024;
+ Thread sender = Thread.ofVirtual().start(() -> forwarder.forwardVote(
+ new Vote("example.test", "TestVoter", "A".repeat(submittedBytes), "TestTimestamp")));
+ try (Socket peer = backend.accept()) {
+ peer.getOutputStream().write("VOTIFIER 2 challenge\n".getBytes(StandardCharsets.UTF_8));
+ assertTrue(writing.await(3, TimeUnit.SECONDS));
+ sender.join(7000);
+ assertFalse(sender.isAlive());
+ assertTrue(smallBuffer.isClosed());
+ peer.setSoTimeout(2000);
+ byte[] partial = peer.getInputStream().readAllBytes();
+ assertTrue(partial.length > 0 && partial.length < submittedBytes,
+ "Peer observed an incomplete write after backpressure");
+ } finally {
+ stopForTest(forwarder);
+ receiver.shutdown();
+ sender.join(2000);
+ }
+ }
+ }
+
+ @Test
+ public void aBlockedCloseRetainsCapacityWithoutBlockingOtherExpirations() throws Throwable {
+ var blocked = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var fastClosed = new CountDownLatch(1);
+ var slowCloses = new AtomicInteger();
+ var quickCloses = new AtomicInteger();
+ var socketCounter = new AtomicInteger();
+ VoteForwarder forwarder = forwarderWithSockets(null, () -> {
+ boolean slow = socketCounter.getAndIncrement() == 0;
+ return new Socket() {
+ @Override
+ public void close() throws IOException {
+ if (slow) {
+ slowCloses.incrementAndGet();
+ blocked.countDown();
+ try {
+ release.await(4, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ } else {
+ quickCloses.incrementAndGet();
+ }
+ super.close();
+ if (!slow) {
+ fastClosed.countDown();
+ }
+ }
+ };
+ });
+ Method register = VoteForwarder.class.getDeclaredMethod("registerAttempt", boolean.class, String.class, long.class);
+ register.setAccessible(true);
+ Method terminated = VoteForwarder.class.getDeclaredMethod("isTerminated");
+ terminated.setAccessible(true);
+ try {
+ call(register, forwarder, true, "direct", System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200));
+ assertTrue(blocked.await(2, TimeUnit.SECONDS));
+ assertThrows(RejectedExecutionException.class, () -> call(register, forwarder, true, "direct",
+ System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
+ call(register, forwarder, false, "runtime", System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200));
+ assertTrue(fastClosed.await(2, TimeUnit.SECONDS));
+ stopForTest(forwarder);
+ assertFalse((boolean) call(terminated, forwarder));
+ assertEquals(1, slowCloses.get());
+ assertEquals(1, quickCloses.get());
+ } finally {
+ release.countDown();
+ stopForTest(forwarder);
+ }
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
+ while (!(boolean) call(terminated, forwarder) && System.nanoTime() < deadline) {
+ Thread.sleep(1);
+ }
+ assertTrue((boolean) call(terminated, forwarder));
+ }
+
+ @Test
+ public void queuedRuntimeCallCanDrainWhileDirectConnectHookSurvivesStop() throws Throwable {
+ var stalled = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var writes = new ByteArrayOutputStream();
+ var socketCount = new AtomicInteger();
+ var target = new ForwardServer(true, "127.0.0.1", 1234, "",
+ KeyGenerator.getInstance("HmacSHA256").generateKey());
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
+ Map.of(), Set.of(), null, Map.of("test", target));
+ var receiver = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), ignored -> {});
+ var forwarder = forwarderWithSockets(receiver, () -> {
+ boolean direct = socketCount.getAndIncrement() == 0;
+ return new Socket() {
+ @Override
+ public void connect(SocketAddress destination, int timeout) throws IOException {
+ if (direct) {
+ stalled.countDown();
+ try {
+ release.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ throw new IOException("synthetic non-cooperative connect hook");
+ }
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return new ByteArrayInputStream("VOTIFIER 2 challenge\r\n".getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Override
+ public OutputStream getOutputStream() {
+ return writes;
+ }
+ };
+ });
+ Method seal = VoteForwarder.class.getDeclaredMethod("sealDirectCalls");
+ seal.setAccessible(true);
+ Method queued = VoteForwarder.class.getDeclaredMethod("forwardQueuedVote", Vote.class);
+ queued.setAccessible(true);
+ Method terminated = VoteForwarder.class.getDeclaredMethod("isTerminated");
+ terminated.setAccessible(true);
+ var vote = new Vote("example.test", "TestVoter", "", "TestTimestamp");
+ Thread direct = Thread.ofVirtual().start(() -> forwarder.forwardVote(vote));
+ try {
+ assertTrue(stalled.await(2, TimeUnit.SECONDS));
+ call(seal, forwarder);
+ forwarder.forwardVote(vote);
+ assertEquals(1, socketCount.get());
+ call(queued, forwarder, vote);
+ assertEquals(2, socketCount.get());
+ assertTrue(writes.toString(StandardCharsets.UTF_8).contains("TestVoter"));
+ stopForTest(forwarder);
+ assertTrue(direct.isAlive());
+ assertFalse((boolean) call(terminated, forwarder));
+ } finally {
+ release.countDown();
+ direct.join(2000);
+ stopForTest(forwarder);
+ receiver.shutdown();
+ }
+ assertFalse(direct.isAlive());
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
+ while (!(boolean) call(terminated, forwarder) && System.nanoTime() < deadline) {
+ Thread.sleep(1);
+ }
+ assertTrue((boolean) call(terminated, forwarder));
+ }
+
+ private static VoteForwarder forwarderWithSockets(VoteReceiver receiver, Supplier sockets) throws Exception {
+ var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class,
+ BiFunction.class, Supplier.class);
+ constructor.setAccessible(true);
+ BiFunction resolve = InetSocketAddress::new;
+ return constructor.newInstance(receiver, 1, resolve, sockets);
+ }
+
+ private static void stopForTest(VoteForwarder forwarder) throws Exception {
+ Method stop = VoteForwarder.class.getDeclaredMethod("stop");
+ stop.setAccessible(true);
+ stop.invoke(forwarder);
+ }
+
+ public static final class SocksClient {
+ public static void main(String[] arguments) throws Exception {
+ var signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ var target = new ForwardServer(true, "127.0.0.1", Integer.parseInt(arguments[0]), "", signingKey);
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
+ Map.of(), Set.of(), null, Map.of("test", target));
+ var receiver = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), accepted -> {});
+ try {
+ new VoteForwarder(receiver).forwardVote(new Vote("example.test", "TestVoter", "", "TestTimestamp"));
+ } finally {
+ receiver.shutdown();
+ }
+ }
+ }
+
private static Object call(Method method, Object receiver, Object... arguments) throws Throwable {
try {
return method.invoke(receiver, arguments);
@@ -253,15 +513,9 @@ private static Object call(Method method, Object receiver, Object... arguments)
}
}
- private static void readSocketHandshake(SocketChannel channel, int timeoutMillis) throws Throwable {
- Method parser = VoteForwarder.class.getDeclaredMethod("readChannelGreeting",
- SocketChannel.class, Selector.class, long.class);
+ private static void readSocketHandshake(Socket socket, int timeoutMillis) throws Throwable {
+ Method parser = VoteForwarder.class.getDeclaredMethod("readSocketGreeting", Socket.class, long.class);
parser.setAccessible(true);
- channel.configureBlocking(false);
- try (Selector selector = Selector.open()) {
- parser.invoke(null, channel, selector, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
- } catch (InvocationTargetException failure) {
- throw failure.getCause();
- }
+ call(parser, null, socket, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
}
}
From 3a707d1537da4411a12dd3dca1fa3ca3a75d2d74 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 23:16:43 +0000
Subject: [PATCH 12/15] Verify forwarding drain and SOCKS deadline boundaries
---
.../votifier/net/VoteForwarder.java | 5 +
.../tests/VoteReceiverLifecycleTest.java | 123 +++++++++++++++-
.../tests/net/VoteForwarderHandshakeTest.java | 135 +++++++++++++++++-
3 files changed, 256 insertions(+), 7 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 746435c..19bae05 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -80,6 +80,11 @@ private static final class Attempt {
private final BiFunction resolveAddress;
private volatile boolean stopped;
+ /**
+ * Creates an independent forwarder using the supplied receiver's configuration.
+ * To share the listener's lifecycle, use its receiver-owned forwarder obtained
+ * from {@link VoteReceiver#getVoteForwarder()} after startup.
+ */
public VoteForwarder(VoteReceiver receiver) {
this(receiver, receiver.getForwardWorkerCount());
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 71f146a..22f7f27 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -7,6 +7,14 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.net.SocketAddress;
+import java.util.function.Supplier;
+import java.util.function.BooleanSupplier;
+import java.util.concurrent.ThreadPoolExecutor;
import java.net.Socket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@@ -418,7 +426,120 @@ public void receiverRetainsStuckResolverAfterNormalAndForcedForwardingDrain() th
}
receiver.shutdown();
}
- assertTrue(receiver.isRetired());
+ waitUntil(receiver::isRetired);
+ }
+ }
+
+ private static void waitUntil(BooleanSupplier condition) throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
+ while (!condition.getAsBoolean() && System.nanoTime() < deadline) {
+ Thread.sleep(1);
+ }
+ assertTrue(condition.getAsBoolean());
+ }
+
+ @Test
+ public void queuedVoteWaitsForRuntimeCloseDuringGracefulDrainAndCancelsDuringForcedDrain() throws Exception {
+ for (boolean forced : new boolean[] {false, true}) {
+ receiver = new CapturingVoteReceiver();
+ receiver.signingKey = KeyGenerator.getInstance("HmacSHA256").generateKey();
+ receiver.servers = Set.of("test");
+ receiver.target = new ForwardServer(true, "127.0.0.1", 1234, "", receiver.signingKey);
+ receiver.start();
+ waitForAccept();
+ var closeEntered = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var writes = new AtomicInteger();
+ var sockets = new AtomicInteger();
+ var firstWorker = new LinkedBlockingQueue();
+ Supplier factory = () -> {
+ boolean first = sockets.getAndIncrement() == 0;
+ return new Socket() {
+ @Override
+ public void connect(SocketAddress address, int timeout) {
+ if (first) {
+ firstWorker.add(Thread.currentThread());
+ }
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return new ByteArrayInputStream("VOTIFIER 2 challenge\n".getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Override
+ public OutputStream getOutputStream() {
+ return new ByteArrayOutputStream() {
+ @Override
+ public void write(byte[] data) throws IOException {
+ writes.incrementAndGet();
+ super.write(data);
+ }
+ };
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (first) {
+ closeEntered.countDown();
+ try {
+ release.await(8, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ super.close();
+ }
+ };
+ };
+ var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class,
+ BiFunction.class, Supplier.class);
+ constructor.setAccessible(true);
+ var forwarderField = VoteReceiver.class.getDeclaredField("voteForwarder");
+ forwarderField.setAccessible(true);
+ var stopForwarder = VoteForwarder.class.getDeclaredMethod("stop");
+ stopForwarder.setAccessible(true);
+ stopForwarder.invoke(receiver.getVoteForwarder());
+ BiFunction resolve = InetSocketAddress::new;
+ forwarderField.set(receiver, constructor.newInstance(receiver, 1, resolve, factory));
+ var executorField = VoteReceiver.class.getDeclaredField("forwardExecutor");
+ executorField.setAccessible(true);
+ var executor = (ThreadPoolExecutor) executorField.get(receiver);
+ int port = receiver.getServer().getLocalPort();
+ var shutdown = new Thread(() -> {
+ if (forced) {
+ Thread.currentThread().interrupt();
+ }
+ receiver.shutdown();
+ });
+ try {
+ VoteReceiverBindingTest.assertVoteAccepted(port, receiver.signingKey);
+ assertTrue(closeEntered.await(2, TimeUnit.SECONDS));
+ VoteReceiverBindingTest.assertVoteAccepted(port, receiver.signingKey);
+ waitUntil(() -> executor.getQueue().size() == 1);
+ Thread worker = firstWorker.poll(2, TimeUnit.SECONDS);
+ assertNotNull(worker);
+ worker.interrupt();
+ waitUntil(() -> executor.getQueue().isEmpty() && worker.getState() == Thread.State.TIMED_WAITING);
+ assertEquals(1, sockets.get());
+ shutdown.start();
+ waitUntil(executor::isShutdown);
+ if (!forced) {
+ release.countDown();
+ }
+ shutdown.join(5000);
+ assertFalse(shutdown.isAlive());
+ assertEquals(forced ? 1 : 2, writes.get());
+ if (forced) {
+ assertFalse(receiver.isRetired());
+ }
+ } finally {
+ release.countDown();
+ shutdown.join(5000);
+ receiver.shutdown();
+ receiver.join(2000);
+ }
+ waitUntil(receiver::isRetired);
}
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index 48f97ee..f02a582 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -253,6 +253,15 @@ public void forwardingPreservesAuthenticatedAndLegacyWirePayloads() throws Excep
@Test
public void separateJvmUsesSocksWithoutConnectingToTheTargetDirectly() throws Exception {
+ checkSocks(false);
+ }
+
+ @Test
+ public void delayedResolutionAndStalledSocksGreetingShareOneBudget() throws Exception {
+ checkSocks(true);
+ }
+
+ private static void checkSocks(boolean stallGreeting) throws Exception {
InetAddress loopback = InetAddress.getByName("127.0.0.1");
try (ServerSocket proxy = new ServerSocket(0, 1, loopback);
ServerSocket directSentinel = new ServerSocket(0, 1, loopback)) {
@@ -262,7 +271,7 @@ public void separateJvmUsesSocksWithoutConnectingToTheTargetDirectly() throws Ex
String classpath = System.getProperty("surefire.test.class.path", System.getProperty("java.class.path"));
Process child = new ProcessBuilder(java, "-DsocksProxyHost=127.0.0.1",
"-DsocksProxyPort=" + proxy.getLocalPort(), "-DsocksNonProxyHosts=", "-cp", classpath,
- SocksClient.class.getName(), Integer.toString(directSentinel.getLocalPort()))
+ SocksClient.class.getName(), Integer.toString(directSentinel.getLocalPort()), Boolean.toString(stallGreeting))
.redirectErrorStream(true).start();
try (Socket peer = proxy.accept()) {
peer.setSoTimeout(3000);
@@ -279,10 +288,16 @@ public void separateJvmUsesSocksWithoutConnectingToTheTargetDirectly() throws Ex
assertEquals("127.0.0.1", InetAddress.getByAddress(in.readNBytes(4)).getHostAddress());
assertEquals(directSentinel.getLocalPort(), in.readUnsignedShort());
out.write(new byte[] {5, 0, 0, 1, 127, 0, 0, 1, 0, 0});
- out.write("VOTIFIER 2 challenge\r\n".getBytes(StandardCharsets.UTF_8));
- String received = new String(in.readAllBytes(), StandardCharsets.UTF_8);
- assertTrue(received.contains("TestVoter"));
- assertTrue(received.endsWith("\r\n"));
+ if (stallGreeting) {
+ peer.setSoTimeout(2600);
+ out.write("VOTIFIER 2 ".getBytes(StandardCharsets.UTF_8));
+ assertEquals(-1, in.read(), "The resolver delay must consume the greeting budget");
+ } else {
+ out.write("VOTIFIER 2 challenge\r\n".getBytes(StandardCharsets.UTF_8));
+ String received = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ assertTrue(received.contains("TestVoter"));
+ assertTrue(received.endsWith("\r\n"));
+ }
assertThrows(SocketTimeoutException.class, directSentinel::accept);
assertTrue(child.waitFor(5, TimeUnit.SECONDS));
assertEquals(0, child.exitValue(), () -> {
@@ -476,6 +491,97 @@ public OutputStream getOutputStream() {
assertTrue((boolean) call(terminated, forwarder));
}
+ @Test
+ public void failedCloseFencesRetirementAndKeepsOneCloseOwner() throws Throwable {
+ var closeCalled = new CountDownLatch(1);
+ var closeCalls = new AtomicInteger();
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
+ Map.of(), Set.of(), null, Map.of());
+ var receiver = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), ignored -> {});
+ var forwarder = forwarderWithSockets(receiver, () -> new Socket() {
+ @Override
+ public void close() throws IOException {
+ closeCalls.incrementAndGet();
+ closeCalled.countDown();
+ throw new IOException("synthetic close failure");
+ }
+ });
+ Method register = VoteForwarder.class.getDeclaredMethod("registerAttempt", boolean.class, String.class, long.class);
+ register.setAccessible(true);
+ Method terminated = VoteForwarder.class.getDeclaredMethod("isTerminated");
+ terminated.setAccessible(true);
+ try {
+ Object attempt = call(register, forwarder, true, "test", System.nanoTime() + TimeUnit.SECONDS.toNanos(4));
+ Method expire = VoteForwarder.class.getDeclaredMethod("expire", attempt.getClass());
+ expire.setAccessible(true);
+ var release = new CountDownLatch(1);
+ var expiry = new FutureTask(() -> {
+ release.await(2, TimeUnit.SECONDS);
+ expire.invoke(forwarder, attempt);
+ return null;
+ });
+ Thread.ofVirtual().start(expiry);
+ release.countDown();
+ stopForTest(forwarder);
+ expiry.get(2, TimeUnit.SECONDS);
+ assertTrue(closeCalled.await(2, TimeUnit.SECONDS));
+ assertEquals(1, closeCalls.get());
+ assertFalse((boolean) call(terminated, forwarder));
+ } finally {
+ stopForTest(forwarder);
+ receiver.shutdown();
+ }
+ }
+
+ @Test
+ public void shutdownCannotOvertakeAReservedSocketBeforeRegistration() throws Exception {
+ var allocating = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var closed = new CountDownLatch(1);
+ var closes = new AtomicInteger();
+ var forwarder = forwarderWithSockets(null, () -> {
+ allocating.countDown();
+ try {
+ release.await(3, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ return new Socket() {
+ @Override
+ public void close() throws IOException {
+ closes.incrementAndGet();
+ super.close();
+ closed.countDown();
+ }
+ };
+ });
+ Method register = VoteForwarder.class.getDeclaredMethod("registerAttempt", boolean.class, String.class, long.class);
+ register.setAccessible(true);
+ var registration = new FutureTask<>(() -> register.invoke(forwarder, false, "runtime",
+ System.nanoTime() + TimeUnit.SECONDS.toNanos(4)));
+ var stopAttempted = new CountDownLatch(1);
+ var stopping = new FutureTask(() -> {
+ stopAttempted.countDown();
+ stopForTest(forwarder);
+ return null;
+ });
+ Thread.ofVirtual().start(registration);
+ try {
+ assertTrue(allocating.await(2, TimeUnit.SECONDS));
+ Thread.ofVirtual().start(stopping);
+ assertTrue(stopAttempted.await(2, TimeUnit.SECONDS));
+ assertThrows(TimeoutException.class, () -> stopping.get(100, TimeUnit.MILLISECONDS));
+ release.countDown();
+ registration.get(2, TimeUnit.SECONDS);
+ stopping.get(2, TimeUnit.SECONDS);
+ assertTrue(closed.await(2, TimeUnit.SECONDS));
+ assertEquals(1, closes.get());
+ } finally {
+ release.countDown();
+ stopForTest(forwarder);
+ }
+ }
+
private static VoteForwarder forwarderWithSockets(VoteReceiver receiver, Supplier sockets) throws Exception {
var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class,
BiFunction.class, Supplier.class);
@@ -497,9 +603,26 @@ public static void main(String[] arguments) throws Exception {
var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
Map.of(), Set.of(), null, Map.of("test", target));
var receiver = VoteReceiver.bind(settings, Logger.getAnonymousLogger(), accepted -> {});
+ VoteForwarder forwarder;
+ if (Boolean.parseBoolean(arguments[1])) {
+ var constructor = VoteForwarder.class.getDeclaredConstructor(VoteReceiver.class, int.class, BiFunction.class);
+ constructor.setAccessible(true);
+ BiFunction delayed = (host, port) -> {
+ try {
+ Thread.sleep(3700);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ return new InetSocketAddress(host, port);
+ };
+ forwarder = constructor.newInstance(receiver, 1, delayed);
+ } else {
+ forwarder = new VoteForwarder(receiver);
+ }
try {
- new VoteForwarder(receiver).forwardVote(new Vote("example.test", "TestVoter", "", "TestTimestamp"));
+ forwarder.forwardVote(new Vote("example.test", "TestVoter", "", "TestTimestamp"));
} finally {
+ stopForTest(forwarder);
receiver.shutdown();
}
}
From 6bd3646cd2fc22f999bc1fc0363fac7a85f0e074 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Fri, 20 Nov 2026 23:20:05 +0000
Subject: [PATCH 13/15] Prove forwarding terminal outcome arbitration
---
.../tests/net/VoteForwarderHandshakeTest.java | 104 +++++++++++++++++-
1 file changed, 103 insertions(+), 1 deletion(-)
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index f02a582..08ffbf4 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -42,6 +42,9 @@
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
@@ -525,14 +528,113 @@ public void close() throws IOException {
stopForTest(forwarder);
expiry.get(2, TimeUnit.SECONDS);
assertTrue(closeCalled.await(2, TimeUnit.SECONDS));
+ for (String poolName : new String[] {"closers", "resolver", "deadlines"}) {
+ var field = VoteForwarder.class.getDeclaredField(poolName);
+ field.setAccessible(true);
+ assertTrue(((java.util.concurrent.ExecutorService) field.get(forwarder)).awaitTermination(2, TimeUnit.SECONDS));
+ }
assertEquals(1, closeCalls.get());
- assertFalse((boolean) call(terminated, forwarder));
+ assertFalse((boolean) call(terminated, forwarder), "A failed close permanently fences retirement");
} finally {
stopForTest(forwarder);
receiver.shutdown();
}
}
+ @Test
+ public void normalCompletionReportsSuccessOnlyWhenItWinsBeforeExpiryOrStop() throws Throwable {
+ for (String winner : new String[] {"completion", "expiry", "stop"}) {
+ var writing = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var closes = new AtomicInteger();
+ var successes = new AtomicInteger();
+ var logger = Logger.getAnonymousLogger();
+ logger.setUseParentHandlers(false);
+ logger.setLevel(Level.ALL);
+ logger.addHandler(new Handler() {
+ @Override
+ public void publish(LogRecord record) {
+ if (record.getMessage().startsWith("Payload forwarded")) {
+ successes.incrementAndGet();
+ }
+ }
+ @Override public void flush() {}
+ @Override public void close() {}
+ });
+ var destination = new ForwardServer(true, "127.0.0.1", 1234, "",
+ KeyGenerator.getInstance("HmacSHA256").generateKey());
+ var settings = new VoteReceiver.Settings("127.0.0.1", 0, "test", true, true, null,
+ Map.of(), Set.of(), null, Map.of("test", destination));
+ var receiver = VoteReceiver.bind(settings, logger, ignored -> {});
+ var forwarder = forwarderWithSockets(receiver, () -> new Socket() {
+ @Override public void connect(SocketAddress address, int timeout) {}
+
+ @Override
+ public InputStream getInputStream() {
+ return new ByteArrayInputStream("VOTIFIER 2 challenge\r\n".getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Override
+ public OutputStream getOutputStream() {
+ return new ByteArrayOutputStream() {
+ @Override
+ public void flush() throws IOException {
+ writing.countDown();
+ try {
+ if (!release.await(3, TimeUnit.SECONDS)) {
+ throw new IOException("test flush was not released");
+ }
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new IOException(ex);
+ }
+ }
+ };
+ }
+
+ @Override
+ public void close() throws IOException {
+ closes.incrementAndGet();
+ super.close();
+ }
+ });
+ var sender = new FutureTask(() -> {
+ forwarder.forwardVote(new Vote("example.test", "TestVoter", "", "TestTimestamp"));
+ return null;
+ });
+ Thread.ofVirtual().start(sender);
+ try {
+ assertTrue(writing.await(2, TimeUnit.SECONDS));
+ if (winner.equals("expiry")) {
+ var attempts = VoteForwarder.class.getDeclaredField("attempts");
+ attempts.setAccessible(true);
+ var lock = VoteForwarder.class.getDeclaredField("lifecycleLock");
+ lock.setAccessible(true);
+ synchronized (lock.get(forwarder)) {
+ Object attempt = ((Set>) attempts.get(forwarder)).iterator().next();
+ Method expire = VoteForwarder.class.getDeclaredMethod("expire", attempt.getClass());
+ expire.setAccessible(true);
+ call(expire, forwarder, attempt);
+ }
+ } else if (winner.equals("stop")) {
+ stopForTest(forwarder);
+ }
+ release.countDown();
+ sender.get(2, TimeUnit.SECONDS);
+ stopForTest(forwarder);
+ var closerField = VoteForwarder.class.getDeclaredField("closers");
+ closerField.setAccessible(true);
+ assertTrue(((ThreadPoolExecutor) closerField.get(forwarder)).awaitTermination(2, TimeUnit.SECONDS));
+ assertEquals(1, closes.get());
+ assertEquals(winner.equals("completion") ? 1 : 0, successes.get());
+ } finally {
+ release.countDown();
+ stopForTest(forwarder);
+ receiver.shutdown();
+ }
+ }
+ }
+
@Test
public void shutdownCannotOvertakeAReservedSocketBeforeRegistration() throws Exception {
var allocating = new CountDownLatch(1);
From db140fd1fb16e37d730abb880b68b1663053bcd2 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Sun, 22 Nov 2026 21:21:19 +0000
Subject: [PATCH 14/15] Count deadline arbitration and strengthen retirement
tests
---
.../votifier/net/VoteForwarder.java | 20 ++++----
.../tests/VoteReceiverLifecycleTest.java | 47 +++++++++++++++----
.../tests/net/VoteForwarderHandshakeTest.java | 40 +++++++++++++---
3 files changed, 84 insertions(+), 23 deletions(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 19bae05..53fb167 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -230,8 +230,9 @@ private void forwardTargets(Vote vote, boolean direct) {
output.flush();
boolean completed;
synchronized (lifecycleLock) {
- completed = !stopped && !attempt.ended && deadline - System.nanoTime() > 0;
- finishAttempt(attempt);
+ boolean expired = deadline - System.nanoTime() <= 0;
+ completed = !stopped && !attempt.ended && !expired;
+ finishAttempt(attempt, !stopped && expired);
}
if (completed) {
receiver.debug("Payload forwarded to " + VoteLogSafety.field(name) + " (" + payload.length + " bytes)");
@@ -248,7 +249,7 @@ private void forwardTargets(Vote vote, boolean direct) {
} finally {
if (attempt != null) {
synchronized (lifecycleLock) {
- finishAttempt(attempt);
+ finishAttempt(attempt, !stopped && deadline - System.nanoTime() <= 0);
awaitClose(attempt, deadline);
}
if (attempt.closeRejected) {
@@ -294,20 +295,23 @@ private Attempt registerAttempt(boolean direct, String name, long deadline) thro
private void expire(Attempt attempt) {
synchronized (lifecycleLock) {
- if (attempt.ended) {
- return;
- }
- expiredAttempts++;
- finishAttempt(attempt);
+ finishAttempt(attempt, true);
}
}
// The only terminal transition and close submission. Caller holds lifecycleLock.
private void finishAttempt(Attempt attempt) {
+ finishAttempt(attempt, false);
+ }
+
+ private void finishAttempt(Attempt attempt, boolean expired) {
if (attempt.ended) {
return;
}
attempt.ended = true;
+ if (expired) {
+ expiredAttempts++;
+ }
if (attempt.timer != null) {
attempt.timer.cancel(false);
}
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
index 22f7f27..5b81195 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/VoteReceiverLifecycleTest.java
@@ -353,17 +353,48 @@ public void repeatedLegacyInitializePreservesTheOriginalListener() throws Except
@Test
public void admittedSocketCloseFailurePreventsRetirementConfirmation() throws Exception {
receiver = new CapturingVoteReceiver();
- receiver.pauseProcessing = true;
var admitted = org.mockito.Mockito.mock(Socket.class);
- org.mockito.Mockito.doThrow(new IOException("synthetic socket close failure")).when(admitted).close();
+ var reading = new CountDownLatch(1);
+ var release = new CountDownLatch(1);
+ var retirementClose = new CountDownLatch(1);
+ Thread retiringThread = Thread.currentThread();
+ var closed = new java.util.concurrent.atomic.AtomicBoolean();
+ org.mockito.Mockito.when(admitted.isClosed()).thenAnswer(invocation -> closed.get());
+ org.mockito.Mockito.when(admitted.getInetAddress()).thenReturn(InetAddress.getLoopbackAddress());
+ org.mockito.Mockito.when(admitted.getOutputStream()).thenReturn(new ByteArrayOutputStream());
+ org.mockito.Mockito.when(admitted.getInputStream()).thenReturn(new InputStream() {
+ @Override
+ public int read() throws IOException {
+ reading.countDown();
+ try {
+ release.await(4, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ return -1;
+ }
+ });
+ org.mockito.Mockito.doAnswer(invocation -> {
+ if (Thread.currentThread() == retiringThread) {
+ retirementClose.countDown();
+ release.countDown();
+ throw new IOException("synthetic socket close failure");
+ }
+ closed.set(true);
+ return null;
+ }).when(admitted).close();
receiver.syntheticSocket = admitted;
receiver.start();
- assertTrue(receiver.thirdAccept.await(2, TimeUnit.SECONDS));
- receiver.shutdown();
- receiver.join(2000);
- assertFalse(receiver.isAlive());
- assertFalse(receiver.isRetired());
- org.mockito.Mockito.verify(admitted, org.mockito.Mockito.atLeastOnce()).close();
+ try {
+ assertTrue(reading.await(2, TimeUnit.SECONDS));
+ receiver.shutdown();
+ receiver.join(2000);
+ assertEquals(0, retirementClose.getCount());
+ assertFalse(receiver.isAlive());
+ assertFalse(receiver.isRetired());
+ } finally {
+ release.countDown();
+ }
}
@Test
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index 08ffbf4..175fd90 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -543,7 +543,7 @@ public void close() throws IOException {
@Test
public void normalCompletionReportsSuccessOnlyWhenItWinsBeforeExpiryOrStop() throws Throwable {
- for (String winner : new String[] {"completion", "expiry", "stop"}) {
+ for (String winner : new String[] {"completion", "expiry", "worker-expiry", "stop"}) {
var writing = new CountDownLatch(1);
var release = new CountDownLatch(1);
var closes = new AtomicInteger();
@@ -581,7 +581,7 @@ public OutputStream getOutputStream() {
public void flush() throws IOException {
writing.countDown();
try {
- if (!release.await(3, TimeUnit.SECONDS)) {
+ if (!release.await(8, TimeUnit.SECONDS)) {
throw new IOException("test flush was not released");
}
} catch (InterruptedException ex) {
@@ -598,6 +598,22 @@ public void close() throws IOException {
super.close();
}
});
+ var timerRelease = new CountDownLatch(1);
+ if (winner.equals("worker-expiry")) {
+ var timerEntered = new CountDownLatch(1);
+ var schedulerField = VoteForwarder.class.getDeclaredField("deadlines");
+ schedulerField.setAccessible(true);
+ var scheduler = (java.util.concurrent.ScheduledThreadPoolExecutor) schedulerField.get(forwarder);
+ scheduler.execute(() -> {
+ timerEntered.countDown();
+ try {
+ timerRelease.await(8, TimeUnit.SECONDS);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ assertTrue(timerEntered.await(2, TimeUnit.SECONDS));
+ }
var sender = new FutureTask(() -> {
forwarder.forwardVote(new Vote("example.test", "TestVoter", "", "TestTimestamp"));
return null;
@@ -616,6 +632,8 @@ public void close() throws IOException {
expire.setAccessible(true);
call(expire, forwarder, attempt);
}
+ } else if (winner.equals("worker-expiry")) {
+ Thread.sleep(5100);
} else if (winner.equals("stop")) {
stopForTest(forwarder);
}
@@ -627,7 +645,11 @@ public void close() throws IOException {
assertTrue(((ThreadPoolExecutor) closerField.get(forwarder)).awaitTermination(2, TimeUnit.SECONDS));
assertEquals(1, closes.get());
assertEquals(winner.equals("completion") ? 1 : 0, successes.get());
+ var expired = VoteForwarder.class.getDeclaredField("expiredAttempts");
+ expired.setAccessible(true);
+ assertEquals(winner.endsWith("expiry") ? 1L : 0L, expired.getLong(forwarder));
} finally {
+ timerRelease.countDown();
release.countDown();
stopForTest(forwarder);
receiver.shutdown();
@@ -661,18 +683,22 @@ public void close() throws IOException {
register.setAccessible(true);
var registration = new FutureTask<>(() -> register.invoke(forwarder, false, "runtime",
System.nanoTime() + TimeUnit.SECONDS.toNanos(4)));
- var stopAttempted = new CountDownLatch(1);
var stopping = new FutureTask(() -> {
- stopAttempted.countDown();
stopForTest(forwarder);
return null;
});
Thread.ofVirtual().start(registration);
try {
assertTrue(allocating.await(2, TimeUnit.SECONDS));
- Thread.ofVirtual().start(stopping);
- assertTrue(stopAttempted.await(2, TimeUnit.SECONDS));
- assertThrows(TimeoutException.class, () -> stopping.get(100, TimeUnit.MILLISECONDS));
+ Thread stopper = Thread.ofPlatform().daemon().start(stopping);
+ long waitUntil = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
+ while (stopper.getState() != Thread.State.BLOCKED && System.nanoTime() < waitUntil) {
+ Thread.sleep(1);
+ }
+ assertEquals(Thread.State.BLOCKED, stopper.getState());
+ assertTrue(java.util.Arrays.stream(stopper.getStackTrace())
+ .anyMatch(frame -> frame.getClassName().equals(VoteForwarder.class.getName())
+ && frame.getMethodName().equals("stop")));
release.countDown();
registration.get(2, TimeUnit.SECONDS);
stopping.get(2, TimeUnit.SECONDS);
From 9558a55282c0dc7c13d950a86f68718e95678901 Mon Sep 17 00:00:00 2001
From: Codex <>
Date: Sun, 22 Nov 2026 21:24:17 +0000
Subject: [PATCH 15/15] Count forwarding expiry before timer installation
---
.../votifier/net/VoteForwarder.java | 2 +-
.../tests/net/VoteForwarderHandshakeTest.java | 33 +++++++++++++++++++
2 files changed, 34 insertions(+), 1 deletion(-)
diff --git a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
index 53fb167..84abfac 100644
--- a/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
+++ b/VotifierPlus/src/main/java/com/vexsoftware/votifier/net/VoteForwarder.java
@@ -286,7 +286,7 @@ private Attempt registerAttempt(boolean direct, String name, long deadline) thro
try {
attempt.timer = deadlines.schedule(() -> expire(attempt), remaining(deadline), TimeUnit.NANOSECONDS);
} catch (Exception ex) {
- finishAttempt(attempt);
+ finishAttempt(attempt, ex instanceof SocketTimeoutException);
throw ex;
}
return attempt;
diff --git a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
index 175fd90..ae1353a 100644
--- a/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
+++ b/VotifierPlus/src/test/java/com/bencodez/votifierplus/tests/net/VoteForwarderHandshakeTest.java
@@ -657,6 +657,39 @@ public void close() throws IOException {
}
}
+ @Test
+ public void expirationDuringSocketRegistrationIsCountedAndClosedOnce() throws Throwable {
+ var closes = new AtomicInteger();
+ var cutoff = new java.util.concurrent.atomic.AtomicLong();
+ var forwarder = forwarderWithSockets(null, () -> {
+ while (cutoff.get() - System.nanoTime() > 0) {
+ java.util.concurrent.locks.LockSupport.parkNanos(cutoff.get() - System.nanoTime());
+ }
+ return new Socket() {
+ @Override
+ public void close() throws IOException {
+ closes.incrementAndGet();
+ super.close();
+ }
+ };
+ });
+ Method register = VoteForwarder.class.getDeclaredMethod("registerAttempt", boolean.class, String.class, long.class);
+ register.setAccessible(true);
+ var expired = VoteForwarder.class.getDeclaredField("expiredAttempts");
+ expired.setAccessible(true);
+ var closer = VoteForwarder.class.getDeclaredField("closers");
+ closer.setAccessible(true);
+ try {
+ cutoff.set(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(500));
+ assertThrows(SocketTimeoutException.class, () -> call(register, forwarder, false, "runtime", cutoff.get()));
+ } finally {
+ stopForTest(forwarder);
+ }
+ assertTrue(((ThreadPoolExecutor) closer.get(forwarder)).awaitTermination(2, TimeUnit.SECONDS));
+ assertEquals(1L, expired.getLong(forwarder));
+ assertEquals(1, closes.get());
+ }
+
@Test
public void shutdownCannotOvertakeAReservedSocketBeforeRegistration() throws Exception {
var allocating = new CountDownLatch(1);