Detect LV Encoding Errors in Receiver

When the length value encoding is violated, which can occur by sending
an incorrect object length to the client, the error is logged and the
receiver continues to run.
This commit is contained in:
Kai S. K. Engelbart 2020-07-03 23:37:25 +02:00
parent d9bf20b88e
commit 19fdb25bfa

View File

@ -51,16 +51,25 @@ public class Receiver extends Thread {
@Override @Override
public void run() { public void run() {
try { while (true) {
while (true) { try {
// Read object length // Read object length
final byte[] lenBytes = new byte[4]; final byte[] lenBytes = new byte[4];
in.read(lenBytes); in.read(lenBytes);
final int len = SerializationUtils.bytesToInt(lenBytes, 0); final int len = SerializationUtils.bytesToInt(lenBytes, 0);
logger.log(Level.FINEST, "Expecting object of length " + len + ".");
// Read object into byte array // Read object into byte array
final byte[] objBytes = new byte[len]; final byte[] objBytes = new byte[len];
in.read(objBytes); final int bytesRead = in.read(objBytes);
logger.log(Level.FINEST, "Read " + bytesRead + " bytes.");
// Catch LV encoding errors
if (len != bytesRead) {
logger.log(Level.WARNING,
String.format("LV encoding violated: expected %d bytes, received %d bytes. Discarding object...", len, bytesRead));
continue;
}
try (ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(objBytes))) { try (ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(objBytes))) {
final Object obj = oin.readObject(); final Object obj = oin.readObject();
@ -69,16 +78,16 @@ public class Receiver extends Thread {
// Get appropriate processor // Get appropriate processor
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
final Consumer processor = processors.get(obj.getClass()); final Consumer processor = processors.get(obj.getClass());
if (processor == null) if (processor == null) logger.log(Level.WARNING,
logger.log(Level.WARNING, String.format( String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
"The received object has the class %s for which no processor is defined.", obj.getClass()));
else processor.accept(obj); else processor.accept(obj);
} }
} catch (final SocketException e) {
// Connection probably closed by client.
return;
} catch (final Exception e) {
logger.log(Level.SEVERE, "Error on receiver thread", e);
} }
} catch (final SocketException e) {
// Connection probably closed by client.
} catch (final Exception e) {
logger.log(Level.SEVERE, "Error on receiver thread", e);
} }
} }