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
1 changed files with 20 additions and 11 deletions

View File

@ -51,16 +51,25 @@ public class Receiver extends Thread {
@Override
public void run() {
try {
while (true) {
while (true) {
try {
// Read object length
final byte[] lenBytes = new byte[4];
in.read(lenBytes);
final int len = SerializationUtils.bytesToInt(lenBytes, 0);
logger.log(Level.FINEST, "Expecting object of length " + len + ".");
// Read object into byte array
final byte[] objBytes = new byte[len];
in.read(objBytes);
final byte[] objBytes = new byte[len];
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))) {
final Object obj = oin.readObject();
@ -69,16 +78,16 @@ public class Receiver extends Thread {
// Get appropriate processor
@SuppressWarnings("rawtypes")
final Consumer processor = processors.get(obj.getClass());
if (processor == null)
logger.log(Level.WARNING, String.format(
"The received object has the class %s for which no processor is defined.", obj.getClass()));
if (processor == null) logger.log(Level.WARNING,
String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
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);
}
}