NetSIDDevDiscovery.java

package builder.netsiddev;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;

import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import static server.netsiddev.NetworkSIDProtocol.DISCOVERY_ID;
import static server.netsiddev.NetworkSIDProtocol.DISCOVERY_PACKET_SIZE;

/** Bounded, cancellable UDP discovery, compatible with JSIDDevice and SID Device. */
public final class NetSIDDevDiscovery implements AutoCloseable {
    /** Time allowed for devices on all local interfaces to answer one search. */
    public static final Duration SEARCH_TIMEOUT = Duration.ofMillis(1500);
    /** Last usable UDP/TCP port; discovery uses the configured device port. */
    public static final int MAX_PORT = 65535;
    /** Periodically check interruption even when the caller does not close us. */
    private static final int RECEIVE_POLL_MILLIS = 100;
    private static final byte[] QUERY = DISCOVERY_ID.getBytes(US_ASCII);

    /** The source endpoint is authoritative; advertised names are display text only. */
    public record Device(InetAddress address, int port, String name, String platform) {
        @Override
        public String toString() {
            return name + " (" + address.getHostAddress() + ":" + port + ") - " + platform;
        }
    }

    private DatagramSocket socket;
    private volatile boolean closed;

    /** Search IPv4 interface broadcasts and local addresses without blocking a UI thread. */
    public List<Device> discover(int port, Duration timeout) throws IOException {
        return discover(port, timeout, broadcastTargets());
    }

    List<Device> discover(int port, Duration timeout, Collection<InetAddress> targets) throws IOException {
        if (port < 1 || port > MAX_PORT || timeout.isNegative() || timeout.isZero()) {
            throw new IllegalArgumentException("A device port and positive discovery timeout are required");
        }
        long timeoutNanos = timeout.toNanos();
        Map<InetSocketAddress, Device> devices = new LinkedHashMap<>();
        DatagramSocket connection = openSocket();
        try (connection) {
            connection.setBroadcast(true);
            long started = System.nanoTime();
            IOException sendFailure = null;
            boolean sent = false;
            for (InetAddress target : targets) {
                checkCancelled();
                try {
                    connection.send(new DatagramPacket(QUERY, QUERY.length, target, port));
                    sent = true;
                } catch (IOException e) {
                    // One unavailable VPN/interface must not suppress other replies.
                    sendFailure = e;
                }
            }
            if (!sent && sendFailure != null) {
                throw sendFailure;
            }
            // The extra byte detects oversized/truncated replies instead of accepting
            // their prefix as a complete hostname/platform description.
            byte[] buffer = new byte[DISCOVERY_PACKET_SIZE + 1];
            DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
            long remaining;
            while ((remaining = timeoutNanos - (System.nanoTime() - started)) > 0) {
                checkCancelled();
                connection.setSoTimeout((int) Math.min(RECEIVE_POLL_MILLIS,
                        Math.max(1, Duration.ofNanos(remaining).toMillis())));
                reply.setLength(buffer.length);
                try {
                    connection.receive(reply);
                    parseResponse(reply).ifPresent(device -> devices.putIfAbsent(
                            new InetSocketAddress(device.address(), device.port()), device));
                } catch (SocketTimeoutException ignored) {
                    // Keep the original deadline, including malformed/duplicate replies.
                }
            }
        } catch (SocketException e) {
            checkCancelled();
            throw e;
        } finally {
            synchronized (this) {
                if (socket == connection) {
                    socket = null;
                }
            }
        }
        checkCancelled();
        List<Device> result = new ArrayList<>(devices.values());
        result.sort(Comparator.comparing(Device::name, String.CASE_INSENSITIVE_ORDER)
                .thenComparing(device -> device.address().getHostAddress()).thenComparingInt(Device::port));
        return List.copyOf(result);
    }

    static Optional<Device> parseResponse(DatagramPacket packet) {
        int length = packet.getLength();
        if (length > DISCOVERY_PACKET_SIZE || packet.getAddress() == null || packet.getPort() < 1) {
            return Optional.empty();
        }
        String response;
        try {
            // Wilfred's Rust responder sends String::as_bytes(), i.e. UTF-8.
            // Reject malformed bytes rather than displaying replacement characters.
            response = UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
                    .onUnmappableCharacter(CodingErrorAction.REPORT)
                    .decode(ByteBuffer.wrap(packet.getData(), packet.getOffset(), length)).toString();
        } catch (CharacterCodingException e) {
            return Optional.empty();
        }
        if (response.codePoints().anyMatch(Character::isISOControl)) {
            return Optional.empty();
        }
        String[] fields = response.split(",", 3);
        if (fields.length != 3 || !DISCOVERY_ID.equals(fields[0]) || fields[1].isBlank() || fields[2].isBlank()) {
            return Optional.empty();
        }
        return Optional.of(new Device(packet.getAddress(), packet.getPort(), fields[1].trim(), fields[2].trim()));
    }

    private static Set<InetAddress> broadcastTargets() throws IOException {
        Set<InetAddress> targets = new LinkedHashSet<>();
        // Loopback also finds a device whose external-connections option is off.
        targets.add(InetAddress.getByName("127.0.0.1"));
        targets.add(InetAddress.getByName("255.255.255.255"));
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces != null && interfaces.hasMoreElements()) {
            NetworkInterface network = interfaces.nextElement();
            try {
                if (!network.isUp()) {
                    continue;
                }
                network.getInterfaceAddresses().forEach(address -> {
                    if (address.getAddress() instanceof Inet4Address) {
                        targets.add(address.getAddress());
                        if (address.getBroadcast() != null) {
                            targets.add(address.getBroadcast());
                        }
                    }
                });
            } catch (SocketException ignored) {
                // An interface can disappear while a VPN or network link changes.
            }
        }
        return targets;
    }

    private synchronized DatagramSocket openSocket() throws SocketException {
        checkCancelled();
        if (socket != null) {
            throw new IllegalStateException("Discovery is already running");
        }
        socket = new DatagramSocket();
        return socket;
    }

    private void checkCancelled() {
        if (closed || Thread.currentThread().isInterrupted()) {
            throw new CancellationException("SID device discovery cancelled");
        }
    }

    /** Closing wakes an outstanding receive immediately, including when the UI closes. */
    @Override
    public synchronized void close() {
        closed = true;
        if (socket != null) {
            socket.close();
        }
    }
}