DetectionThread.java
package server.netsiddev;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
import java.util.function.BooleanSupplier;
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;
/** Answers SID Device UDP discovery on the same bound address and port as TCP. */
public class DetectionThread extends Thread implements AutoCloseable {
private final DatagramSocket socket;
private final BooleanSupplier allowExternalConnections;
private final byte[] response;
/**
* The TCP listener owns this responder and replaces it whenever its binding
* changes. A local-only TCP socket must not advertise a wildcard UDP endpoint.
*
* @param listeningAddress the TCP socket's actual bound address and port
* @param allowExternalConnections access policy for that listener
*/
public DetectionThread(InetSocketAddress listeningAddress, BooleanSupplier allowExternalConnections) {
super("JSIDDevice-Discovery");
this.allowExternalConnections = allowExternalConnections;
String systemName;
try {
systemName = InetAddress.getLocalHost().getHostName();
} catch (IOException e) {
systemName = "localhost";
}
String osArch = is64Bit() ? "64-bit" : "32-bit";
response = (DISCOVERY_ID + "," + systemName + "," + System.getProperty("os.name") + " " + osArch)
.getBytes(UTF_8);
DatagramSocket connection = null;
try {
connection = new DatagramSocket(listeningAddress);
} catch (SocketException e) {
System.err.println("Cannot start SID device discovery on " + listeningAddress + ": " + e.getMessage());
}
socket = connection;
}
@Override
public void run() {
if (socket == null) {
return;
}
byte[] buffer = new byte[DISCOVERY_PACKET_SIZE];
byte[] query = DISCOVERY_ID.getBytes(US_ASCII);
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
try {
while (!socket.isClosed()) {
// receive() changes the packet length; restore its capacity after
// short/malformed packets so a later complete query is not truncated.
incoming.setLength(buffer.length);
socket.receive(incoming);
// Preserve compatibility with clients that append padding/suffix bytes.
if (incoming.getLength() >= query.length
&& Arrays.equals(buffer, 0, query.length, query, 0, query.length)
&& (isLocalAddress(incoming.getAddress()) || allowExternalConnections.getAsBoolean())) {
socket.send(new DatagramPacket(response, response.length, incoming.getAddress(), incoming.getPort()));
}
}
} catch (IOException e) {
if (!socket.isClosed()) {
e.printStackTrace();
}
} finally {
close();
}
}
/** Identify callers on this machine; discovery still obeys the TCP bind address. */
static boolean isLocalAddress(InetAddress address) throws SocketException {
return address.isLoopbackAddress() || NetworkInterface.getByInetAddress(address) != null;
}
int getPort() {
return socket == null ? -1 : socket.getLocalPort();
}
@Override
public void close() {
if (socket != null) {
socket.close();
}
}
private static boolean is64Bit() {
final String arch = System.getProperty("os.arch");
final String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
return arch != null && arch.contains("64") || wow64Arch != null && wow64Arch.contains("64");
}
}